给一个不多于五位的正整数c++
时间: 2024-06-13 22:03:57 浏览: 16
这是一个用C++编写的程序,可以输入一个不多于5位的正整数,并实现以下功能:
(1)求出它是几位数;
(2)分别打印出每一位数字;
(3)按逆序打印出各位数字。
该程序使用了数组和循环语句,可以通过输入一个正整数,将其转化为数组中的每一位数字,并按照要求输出。以下是该程序的代码:
```
#include <iostream>
using namespace std;
int main() {
int num, a[5], i, j;
cin >> num;
for (i = 0; i < 5 && num > 0; i++) {
a[i] = num % 10; num /= 10;
}
cout << i << endl;
for (j = i - 1; j >= 0; j--) {
if (j == i - 1) {
cout << a[j];
} else {
cout << " " << a[j];
}
}
cout << endl;
for (j = 0; j < i; j++) {
if (j == 0) {
cout << a[j];
} else {
cout << " " << a[j];
}
}
return 0;
}
```
相关问题
用c++编写给一个不多于5位的正整数,要求:①求出它是几位数;②分别打印出每一位数字;③按逆序打印出各位数字,例如原数是321,应输出123。
好的,这是一个简单的实现,以下是代码:
```c++
#include <iostream>
using namespace std;
int main() {
int num, digit = 0, temp;
cout << "请输入一个不多于5位的正整数:";
cin >> num;
if (num >= 10000 || num <= 0) {
cout << "输入错误,请重新输入!" << endl;
return 0;
}
temp = num;
//求出它是几位数
while (temp != 0) {
temp /= 10;
digit++;
}
cout << num << "是" << digit << "位数" << endl;
//分别打印出每一位数字
temp = num;
for (int i = digit - 1; i >= 0; i--) {
int base = pow(10, i);
cout << temp / base << " ";
temp %= base;
}
cout << endl;
//按逆序打印出各位数字
temp = num;
while (temp != 0) {
cout << temp % 10;
temp /= 10;
}
cout << endl;
return 0;
}
```
程序运行后,会提示您输入一个不多于5位的正整数,然后根据输入的数字,求出它的位数、每一位数字,并按逆序打印出各位数字。注意,这个程序只是一个简单的实现,实际上需要考虑更多的错误处理,如输入负数、输入超过5位数的数字等。
、 给一个不多于 5位的正整数,要求: 一、求它是几位数, 逆序打印出各位数字,要求使用指针完成逆序打印的功能。
好的,我可以回答你的问题。这个问题可以用指针来解决,可以按照以下步骤来实现:
1. 定义一个 int 类型的变量来存储输入的正整数;
2. 声明一个 int 类型的指针变量 p,将其指向该变量;
3. 通过循环语句,将该正整数逆序输出,每次输出一个数字;
4. 输出完成后,将指针 p 指向空,释放内存。
下面是 C++ 代码示例:
```c++
#include <iostream>
using namespace std;
int main()
{
int num, len = 0;
int* p;
cout << "请输入一个不多于5位的正整数:";
cin >> num;
p = #
while (*p != 0)
{
cout << *p % 10;
*p /= 10;
len++;
}
cout << endl << "该正整数是" << len << "位数。" << endl;
return 0;
}
```
希望这个回答能够帮助到你!
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)