分别用for. while 和do-while循环语句以及递归方法计算n,并输出算式。
时间: 2024-01-24 10:16:45 浏览: 83
练习使用for、while、do while、foreach in等循环语句
假设需要计算n的阶乘,即n!的结果,以下是使用不同循环语句和递归方法计算n!并输出算式的示例代码:
1. for循环
```python
n = int(input("请输入一个正整数:"))
result = 1
for i in range(1, n+1):
result *= i
print(str(i) + " * ", end="")
print("= " + str(result))
```
2. while循环
```python
n = int(input("请输入一个正整数:"))
result = 1
i = 1
while i <= n:
result *= i
if i != n:
print(str(i) + " * ", end="")
else:
print(str(i) + " = ", end="")
i += 1
print(str(result))
```
3. do-while循环(Python中没有do-while循环,可以使用while True和break语句模拟)
```python
n = int(input("请输入一个正整数:"))
result = 1
i = 1
while True:
result *= i
if i != n:
print(str(i) + " * ", end="")
else:
print(str(i) + " = ", end="")
break
i += 1
print(str(result))
```
4. 递归方法
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
n = int(input("请输入一个正整数:"))
result = factorial(n)
for i in range(1, n+1):
if i != n:
print(str(i) + " * ", end="")
else:
print(str(i) + " = ", end="")
print(str(result))
```
阅读全文