Write a program to print all digits of a given number by using a recursive function.
时间: 2024-05-06 18:17:27 浏览: 119
输出n个数字的全排列(可重复)
4星 · 用户满意度95%
Here's the Python code to print all digits of a given number using a recursive function:
```
def print_digits(n):
if n < 10:
print(n)
else:
print_digits(n // 10)
print(n % 10)
# Example usage:
print_digits(12345) # Output: 1 2 3 4 5
```
In this code, the `print_digits` function takes an integer `n` as input. If `n` is less than 10, we simply print it. Otherwise, we first call the `print_digits` function recursively with `n // 10`, which gives us all the digits except for the last one. Then, we print the last digit by computing `n % 10`. This way, we print the digits in reverse order (from right to left).
阅读全文