C语言如何计算阶乘?
时间: 2024-12-12 12:17:13 浏览: 2
在C语言中,计算阶乘(factorial)可以通过递归或循环的方式实现。这里我会给你两种常见的方法:
**1. 递归法:**
```c
#include <stdio.h>
unsigned long long factorial(int n) {
if (n == 0 || n == 1) { // 阶乘的基础情况
return 1;
} else {
return n * factorial(n - 1); // 递归调用
}
}
int main() {
int num;
printf("Enter a non-negative integer: ");
scanf("%d", &num);
if (num >= 0) {
unsigned long long result = factorial(num);
printf("The factorial of %d is %llu\n", num, result);
} else {
printf("Invalid input. Please enter a non-negative number.\n");
}
return 0;
}
```
**2. 循环法:**
```c
#include <stdio.h>
unsigned long long factorial(int n) {
unsigned long long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
int main() {
int num;
printf("Enter a non-negative integer: ");
scanf("%d", &num);
if (num >= 0) {
unsigned long long result = factorial(num);
printf("The factorial of %d is %llu\n", num, result);
} else {
printf("Invalid input. Please enter a non-negative number.\n");
}
return 0;
}
```
这两种方法都可以有效地计算非负整数的阶乘,但请注意,对于较大的数值,递归可能会导致栈溢出,因此循环法更为稳健。
阅读全文