Skip to content

Commit 46b07f2

Browse files
authored
Update 分别用递归法和迭代法求阶乘.c
1 parent a1d55a0 commit 46b07f2

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed
Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,42 @@
1-
#
1+
#include <stdio.h>
2+
#include <time.h>
3+
4+
// 递归计算阶乘
5+
long factorial_recursion(int n){
6+
if(n<=0){
7+
return 1;
8+
}else{
9+
return n * factorial_recursion(n-1);
10+
}
11+
}
12+
13+
// 迭代计算阶乘
14+
long factorial_iteration(int n){
15+
int result = 1;
16+
17+
while(n>1){
18+
result *= n;
19+
n--;
20+
}
21+
22+
return result;
23+
}
24+
25+
26+
int main(){
27+
int N = 10;
28+
long recursion_result = factorial_recursion(N);
29+
long iteration_result = factorial_iteration(N);
30+
31+
// %ld 输出长整型,即 long int
32+
printf("The factorial(recursion) of %ld is %ld!\n", N, recursion_result);
33+
printf("The factorial(iteration) of %ld is %ld!\n", N, iteration_result);
34+
35+
return 0;
36+
}
37+
38+
39+
//运行结果:
40+
41+
//The factorial(recursion) of 10 is 3628800!
42+
//The factorial(iteration) of 10 is 3628800!

0 commit comments

Comments
 (0)