在C语言中,计算阶乘可以通过以下几种方法实现:
递归方法
```c
long long factorial(int n) {
if (n == 0) return 1;
else return n * factorial(n - 1);
}
循环方法
```c
long long factorial(int n) {
long long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
使用数组存储阶乘结果(例如计算100的阶乘):
```c
include
int main() {
int n = 100, p = 0, mp = 0, temp;
int a = {1};
for (int i = 1; i <= n; i++) {
temp = i;
while (temp > 0) {
a[p] = temp % 10;
p++;
temp /= 10;
}
p--;
mp = p > mp ? p : mp;
}
mp++;
while (mp--) {
printf("%d", a[mp]);
}
return 0;
}
使用标准库函数(例如使用`math.h`中的`pow`函数):
```c
include
include
int main() {
int n;
printf("输入一个整数: ");
scanf("%d", &n);
printf("%d! = %.0Lf\n", n, pow(n, n) / factorial(n));
return 0;
}
请注意,当计算较大数的阶乘时,结果可能会超出`int`或`long long`类型的范围,此时需要使用更大范围的整数类型,如高精度库或自定义大整数类型。
您可以根据需要选择合适的方法来计算阶乘