计算1!+2!+3!+...+9!
时间: 2024-01-09 10:23:07 浏览: 205
c++ 1!+2!+3!+..
以下是两种计算1!+2!+3!+...+9!的方法:
1. 使用for循环和阶乘函数来计算:
```python
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
sum = 0
for i in range(1, 10):
sum += factorial(i)
print(sum) # 输出:409113
```
2. 使用递归函数来计算:
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def sum_factorial(n):
if n == 1:
return 1
else:
return factorial(n) + sum_factorial(n-1)
print(sum_factorial(9)) # 输出:409113
```
阅读全文