用c++输入一个4位的正整数,并倒序输出
时间: 2024-05-16 16:13:37 浏览: 21
以下是一个示例代码:
```cpp
#include <iostream>
using namespace std;
int main() {
int num;
cout << "请输入一个4位正整数:";
cin >> num;
int a = num % 10; // 取个位数
int b = num / 10 % 10; // 取十位数
int c = num / 100 % 10; // 取百位数
int d = num / 1000; // 取千位数
cout << "倒序输出为:" << a << b << c << d << endl;
return 0;
}
```
输入一个4位正整数后,首先通过取模和除法操作获取各个位数的数字,然后按照倒序输出即可。注意,输出时需要使用空格或换行符隔开各个数字。
相关问题
从键盘输入一个三正整数n,将整数n的个位,十位,百位倒序生成一个新数字并进行输出
好的,这是一个简单的编程问题。以下是该问题的C++代码实现:
```c++
#include <iostream>
using namespace std;
int main() {
int n, reverse_n = 0;
cin >> n;
while (n > 0) {
int digit = n % 10;
reverse_n = reverse_n * 10 + digit;
n /= 10;
}
cout << reverse_n << endl;
return 0;
}
```
输入一个三位正整数,比如说 123,程序会将其个位、十位、百位倒序,输出 321。
c++输入一个正整数,然后把该整数的每一位数字从高位到低位顺序输出,每个数字占一行。
```python
num = int(input("请输入一个正整数: "))
while num > 0:
digit = num % 10 # 取出最低位数字
print(digit) # 输出最低位数字
num //= 10 # 去掉最低位数字
```
或者使用字符串切片:
```python
num = input("请输入一个正整数: ")
for digit in num[::-1]:
print(digit)
```
注意:这里使用了 Python 中的整除运算符 `//`,它可以直接将结果转换为整数类型,而不是浮点数类型。而在第二种方法中,输入的数字被当作字符串处理,因此需要使用字符串切片来倒序输出每一位数字。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)