利用求阶乘函数Fact(),编程计算并输出1! + 2! + …+ n!的值
时间: 2023-10-06 17:06:16 浏览: 202
以下是Python的代码实现:
```python
def Fact(n):
if n == 0:
return 1
else:
return n * Fact(n-1)
def sum_of_factorials(n):
sum = 0
for i in range(1, n+1):
sum += Fact(i)
return sum
n = int(input("请输入n的值:"))
print("1! + 2! + ... + n! 的值为:", sum_of_factorials(n))
```
示例输入输出:
```
请输入n的值:5
1! + 2! + ... + n! 的值为: 153
```
相关问题
C语言,利用求阶乘函数fact,编程计算并输出1!+2!+...+n!的值
以下是C语言实现计算1!+2!+3!+……+n!的代码,其中利用了求阶乘函数fact(n):
```c
#include <stdio.h>
double fact(int n) {
double res = 1;
for (int i = 1; i <= n; i++) {
res *= i;
}
return res;
}
double fun(int n) {
double res = 0;
for (int i = 1; i <= n; i++) {
res += fact(i);
}
return res;
}
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
printf("%.0f\n", fun(n));
return 0;
}
```
利用求阶乘函数Fact(),编程计算并输出1!+2!+……+n!的值
以下是利用求阶乘函数Fact(),编程计算并输出1!+2!+……+n!的值的C语言代码:
```c
#include <stdio.h>
int Fact(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * Fact(n - 1);
}
}
int main() {
int n, sum = 0;
printf("请输入一个正整数n:");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += Fact(i);
}
printf("1!+2!+...+%d!的值为:%d\n", n, sum);
return 0;
}
```
运行结果如下:
```
请输入一个正整数n:5
1!+2!+...+5!的值为:153
```
阅读全文