python计算1!+ 2!+ 3!+ ... +n!的值
时间: 2023-12-07 20:38:43 浏览: 166
1_求1!+2!+...n!的值.c
以下是两种Python计算1!+2!+3!+...+n!的方法:
1.使用for循环计算阶乘和
```python
n = int(input("请输入一个正整数:"))
sum = 0
factorial = 1
for i in range(1, n+1):
factorial *= i
sum += factorial
print("1!+2!+3!+...+n!的值为:", sum)
```
2.使用递归函数调用阶乘方法求和
```python
def jie(n):
if n == 1:
return 1
else:
return n*jie(n-1)
n = int(input("请输入一个正整数:"))
sum = 0
if n < 1 or n > 40:
print("请重新输入数据")
else:
for i in range(1, n+1):
sum += jie(i)
print("1!+2!+3!+...+n!的值为:", sum)
```
阅读全文