无法在C中使用阶乘函数

Léo*_* 준영 0 c factorial

我无法使用以下代码.

#include <stdio.h>

// I am not sure whethere I should void here or not.
int main() {
    // when the first bug is solved, I put here arg[0]. It should be
    // similar command line parameter as args[0] in Java.
    int a=3;                  
    int b; 
    b = factorial(a);

    // bug seems to be here, since the %1i seems to work only in fprintf
    printf("%1i", b);
    return 0;      
}  

int factorial(int x) {
    int i; 
    for(i=1; i<x; i++) 
        x *= i; 
    return x; 
}  
Run Code Online (Sandbox Code Playgroud)

你怎么能让代码工作?

Aln*_*tak 15

您正在循环中修改循环终止变量(x).目前你的代码在几次迭代后爆炸,当x溢出32位整数的范围然后变为负数且非常大时,因此终止循环.

它应该是:

int factorial(int n) {
    int i, x = 1;
    for (i = 2; i <= n; ++i) {
        x *= i;
    }
    return x;
}
Run Code Online (Sandbox Code Playgroud)

更好的是,你应该使用long而不是int变量x和返回值,因为n!变得非常快.


Bil*_*ard 9

AInitak给了正确的答案,但我想补充一点,你可以在一个方式找到您的代码中的bug是打印出来的值i,并x在阶乘循环.

int factorial(int x) {
    int i;
    for(i=1; i<x; i++)
    {
        x *= i;
        printf("%d, %d\n", i, x);
    }
    return x;
}
Run Code Online (Sandbox Code Playgroud)

这给你输出

1, 3
2, 6
3, 18
4, 72
5, 360
6, 2160
7, 15120
8, 120960
9, 1088640
10, 10886400
11, 119750400
12, 1437004800
13, 1501193216
14, -458131456
-458131456
Run Code Online (Sandbox Code Playgroud)

这样可以更容易地看出出了什么问题.由于AInitak解释的原因,循环不会停在您期望的位置.