求Sn=1!+2!+3!+4!+5!+…+n!之值
时间: 2023-12-01 21:42:32 浏览: 79
计算 S=1!+2!+3!+...+N!。
以下是两种求Sn=1!+2!+3!+4!+5!+…+n!之值的方法:
1.使用for循环计算阶乘和
```python
n = int(input("请输入n的值:"))
sum = 0
factorial = 1
for i in range(1, n+1):
factorial *= i
sum += factorial
print("Sn的值为:", sum)
```
2.使用递归函数计算阶乘和
```python
def factorial(n):
if n == 1:
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("Sn的值为:", sum)
```
阅读全文