编写并测试函数reverse(x),输入一/个整数,将各位数字反转后输出。 点击复制后,将打开C知道体验页
时间: 2024-06-03 07:07:45 浏览: 11
#include <stdio.h>
int reverse(int x){
int res = 0;
while(x != 0){
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
int main(){
int x;
printf("请输入一个整数:");
scanf("%d", &x);
printf("反转后的数字为:%d", reverse(x));
return 0;
}
相关问题
用python编写并测试函数reverse(x),输入一/个整数,将各位数字反转后输出。 点击复制后,将打开C知道体验页
def reverse(x):
if x < 0: # 如果是负数,先转为正数再反转
x = -x
x_str = str(x)[::-1]
x = -int(x_str)
else:
x_str = str(x)[::-1]
x = int(x_str)
return x
# 测试
print(reverse(12345)) # 输出 54321
print(reverse(-12345)) # 输出 -54321
用Python编写并测试函数reverse(x),输入一个整数,将各位数字反转后输出
好的,我知道了,这是您问我如何用 Python 编写并测试函数 reverse(x),下面是一段示例代码:
```python
def reverse(x):
"""
输入一个整数,将各位数字反转后输出。
"""
if x < 0:
x = -x
flag = -1
else:
flag = 1
res = 0
while x > 0:
res = res * 10 + x % 10
x //= 10
return flag * res
# 测试示例
print(reverse(123)) # 输出 321
print(reverse(-123)) # 输出 -321
print(reverse(120)) # 输出 21
```
这段代码实现了将一个整数各位数字反转后输出的功能,我们将正负数都看作一个整体,通过取模和整除运算实现反转,同时根据输入的正负号返回正确的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)