计算 c 语言中求整数阶乘有递归、循环和迭代 3 种方法,对于较小 n 值(n
C 语言中计算阶乘
在 C 语言中,求一个整数的阶乘有以下几种方法:
1. 递归方法
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
2. 循环方法
int factorial(int n) {
int result = 1;
for (int i = 1; i <p><strong>3. 迭代方法</strong></p><pre class="brush:php;toolbar:false">int factorial(int n) {
int result = 1;
while (n > 0) {
result *= n;
n--;
}
return result;
}
哪种方法更好?
对于较小的 n 值(例如 n
示例
计算 5 的阶乘:
int result = factorial(5);
printf("5 的阶乘是 %dn", result);
输出:
5 的阶乘是 120