递归实现逆序输出整数
时间: 2024-06-13 18:06:04 浏览: 11
以下是递归实现逆序输出整数的Python代码:
```python
def reverse(n):
if n == 0:
return
print(n % 10, end='')
reverse(n // 10)
n = int(input())
reverse(n)
```
输入一个正整数n,然后调用reverse函数,该函数会递归地将n的个位数输出,并将n除以10向下取整,直到n为0为止。需要注意的是,为了保证输出的数字是连续的,我们在print函数中使用了end=''参数,将默认的换行符改为空字符串。
相关问题
C++递归实现逆序输出整数
可以使用递归函数将整数倒序输出,具体实现如下:
```c++
#include <iostream>
using namespace std;
void reverse(int n) {
if (n == 0) return; // 递归结束条件
cout << n % 10; // 输出最后一位数字
reverse(n / 10); // 递归调用函数
}
int main() {
int n;
cout << "请输入一个整数:";
cin >> n;
cout << "逆序输出结果为:";
reverse(n);
cout << endl;
return 0;
}
```
递归函数 `reverse()` 的参数为待倒序输出的整数 `n`,如果 `n` 等于 0,则递归结束;否则,先输出 `n` 的最后一位数字,再将 `n` 除以 10(向下取整),继续调用 `reverse()` 函数,直到 `n` 等于 0。最后在 `main()` 函数中输入一个整数,调用 `reverse()` 函数实现逆序输出。
用python递归实现逆序输出任意整数
以下是用Python递归实现逆序输出任意整数的代码:
```python
def reverse_num(num):
if num < 10:
print(num)
else:
print(num % 10, end="")
reverse_num(num // 10)
num = int(input("请输入一个整数:"))
print("逆序输出:", end="")
reverse_num(num)
```
输入一个整数后,调用`reverse_num`函数开始递归。如果输入的数小于10,直接输出;否则,先输出这个数的个位数,再将这个数除以10向下取整(即去掉个位数),并将结果传入函数中继续递归。当传入的数小于10时,递归结束,函数开始一层层返回。每层返回时,都会输出该层所处理的数的个位数,从而实现逆序输出整数的效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)