求1到20的阶层和c语言
时间: 2024-11-13 20:25:15 浏览: 17
1到20的阶乘分别为:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000
在C语言中,可以使用循环和递归两种方式来计算阶乘。以下是两种方式的代码示例:
使用循环计算阶乘:
```c
#include <stdio.h>
int main() {
int n = 20;
long long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
printf("20! = %lld\n", factorial);
return 0;
}
```
使用递归计算阶乘:
```c
#include <stdio.h>
long long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n = 20;
long long result = factorial(n);
printf("20! = %lld\n", result);
return 0;
}
```
阅读全文