输入一个整数n,求1!+2!+...+n!
时间: 2023-11-24 13:06:54 浏览: 96
1!+2!+..n!
以下是两种Python求1!+2!+...+n!的方法:
方法一:使用循环和递归计算阶乘并求和
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n = int(input("请输入一个整数n:"))
sum = 0
for i in range(1, n+1):
sum += factorial(i)
print("1!+2!+...+n!的和为:", sum)
```
方法二:使用循环计算阶乘并求和
```python
n = int(input("请输入一个整数n:"))
sum = 0
factorial = 1
for i in range(1, n+1):
factorial *= i
sum += factorial
print("1!+2!+...+n!的和为:", sum)
```
阅读全文