给出一个不多于5位的整数,要求 1、求出它是几位数 2、分别输出每一位数字 3、按逆序输出各位数字,例如原数为321,应输出123 输入
时间: 2023-12-19 10:29:04 浏览: 39
下面是实现该功能的C++代码:
```
#include <iostream>
using namespace std;
int main() {
int num;
cout << "请输入一个不多于5位的整数:";
cin >> num;
// 判断位数
int digit = 0;
if (num == 0) {
digit = 1;
} else {
while (num > 0) {
digit++;
num /= 10;
}
}
cout << "该数是" << digit << "位数" << endl;
// 分别输出每一位数字
int temp = num;
for (int i = digit; i > 0; i--) {
int n = temp / pow(10, i - 1);
cout << n << " ";
temp = temp % (int)pow(10, i - 1);
}
cout << endl;
// 按逆序输出各位数字
while (num > 0) {
cout << num % 10;
num /= 10;
}
cout << endl;
return 0;
}
```
相关问题
c++给出一个不多于5位的整数,要求 1、求出它是几位数 2、分别输出每一位数字 3、按逆序输出各位数字,
好的,以下是C++代码:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入一个不多于5位的整数:" << endl;
cin >> n;
// 判断几位数
int digit;
if (n < 10) {
digit = 1;
} else if (n < 100) {
digit = 2;
} else if (n < 1000) {
digit = 3;
} else if (n < 10000) {
digit = 4;
} else {
digit = 5;
}
cout << "它是" << digit << "位数" << endl;
// 分别输出每一位数字
int temp = n;
int a[5];
for (int i = 0; i < digit; i++) {
a[i] = temp % 10;
temp /= 10;
}
cout << "每一位数字分别为:";
for (int i = digit - 1; i >= 0; i--) {
cout << a[i] << " ";
}
cout << endl;
// 按逆序输出各位数字
cout << "按逆序输出各位数字为:";
for (int i = 0; i < digit; i++) {
cout << a[i];
}
cout << endl;
return 0;
}
```
输入一个不多于5位的整数后,程序会输出它是几位数,每一位数字分别是什么,以及按逆序输出各位数字。注意,以上程序只适用于正整数或0,如果输入负数会出现错误。
从键盘输入一个不多于3位的正整数,求它是几位数字,分别输出每一位数字
以下是C语言的代码实现,可以从键盘输入一个不多于3位的正整数,求它是几位数字,分别输出每一位数字:
```c
#include <stdio.h>
int main() {
int num, digit, count = 0;
printf("请输入一个不多于3位的正整数:");
scanf("%d", &num);
int temp = num;
while (temp != 0) {
digit = temp % 10;
printf("第%d位数字为:%d\n", ++count, digit);
temp /= 10;
}
printf("该数是%d位数字\n", count);
return 0;
}
```
输入一个不多于3位的正整数,程序会先通过`scanf`函数获取输入的数字,然后使用`while`循环,每次取出数字的个位数并输出,同时将计数器`count`加1,直到数字变为0。最后输出数字的位数。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)