用函数的方法求1!+2!+3!+...n!
时间: 2023-12-07 16:38:54 浏览: 82
python计算阶乘和的方法(1!+2!+3!+...+n!)
5星 · 资源好评率100%
以下是两种方法求1!+2!+3!+...+n!的和:
1. C语言实现:
```c
#include <stdio.h>
long fun(int n)
{
if (n == 1)
return 1;
else
return n * fun(n - 1);
}
long sum(int n)
{
long s = 0;
for (int i = 1; i <= n; i++)
{
s += fun(i);
}
return s;
}
int main()
{
int n;
printf("请输入n的值:");
scanf("%d", &n);
printf("%d的阶乘和为:%ld\n", n, sum(n));
return 0;
}
```
2. Python实现:
```python
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
def sum_factorial(n):
s = 0
for i in range(1, n+1):
s += factorial(i)
return s
n = int(input("请输入n的值:"))
print("{}的阶乘和为:{}".format(n, sum_factorial(n)))
```
阅读全文