求1!+2!+3!+、、、+n!(用函数实现) 输入:5 输出:1!+2!+...+5!=153
时间: 2023-09-19 14:09:19 浏览: 55
c++ 1!+2!+3!+..
以下是Python实现的代码:
```python
def factorial(n):
"""
计算n的阶乘
"""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
def sum_factorial(n):
"""
计算1!+2!+...+n!
"""
sum = 0
for i in range(1, n+1):
sum += factorial(i)
return sum
n = int(input("请输入一个正整数n:"))
result = sum_factorial(n)
print("1!+2!+...+{}!={}".format(n, result))
```
运行结果:
```
请输入一个正整数n:5
1!+2!+...+5!=153
```
阅读全文