实验10-3 递归求阶乘和(15 分)

实验10-3 递归求阶乘和(15 分)

本题要求实现一个计算非负整数阶乘的简单函数,并利用该函数求 $1!+2!+3!+\cdots+n! $的值。

函数接口定义:

1
2
double fact( int n );
double factsum( int n );

函数fact应返回n的阶乘,建议用递归实现。函数factsum应返回 1!+2!+…+n! 的值。题目保证输入输出在双精度范围内。

裁判测试程序样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>

double fact( int n );
double factsum( int n );

int main()
{
int n;

scanf("%d",&n);
printf("fact(%d) = %.0f\n", n, fact(n));
printf("sum = %.0f\n", factsum(n));

return 0;
}

/* 你的代码将被嵌在这里 */

输入样例1:

1
10

输出样例1:

1
2
fact(10) = 3628800
sum = 4037913

输入样例2:

1
0

输出样例2:

1
2
fact(0) = 1
sum = 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdio.h>

double fact( int n );
double factsum( int n );

int main()
{
int n;

scanf("%d",&n);
printf("fact(%d) = %.0f\n", n, fact(n));
printf("sum = %.0f\n", factsum(n));

return 0;
}
double fact(int n)
{
double result;

if (n == 0 || n == 1)
result = 1;
else
result = n*fact(n-1);

return result;
}

double factsum(int n)
{
int i;
double sum;
sum=0;
for (i=1; i<=n; i++)
sum = sum+fact(i);
return sum;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×