c - 无法使阶乘函数在 C 中工作

标签 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; 
}  

如何让代码工作?

最佳答案

您正在修改循环内的循环终止变量 (x)。目前,当 x 溢出 32 位整数的范围,然后变为负数且非常大时,您的代码在几次迭代后就会崩溃,从而终止循环。

应该是:

int factorial(int n) {
    int i, x = 1;
    for (i = 2; i <= n; ++i) {
        x *= i;
    }
    return x;
}

更好的是,对于变量 x 和返回值,您应该使用 long 而不是 int,因为 n! 很快变得非常大。

关于c - 无法使阶乘函数在 C 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/843188/

相关文章:

java - (Java) 如何使用扩展精度算术来处理更大的阶乘?

java - 如何在不使用 java 中的递归或循环的情况下查找阶乘?

c - 什么决定了两个结构成员之间的距离?

c - "undefined behaviour"和 "implementation defined behaviour"之间有什么区别,或者为什么还要区分它们?

c - 具有自己的文件偏移量的重复文件描述符

python - 你如何在 python 中进行双阶乘?

algorithm - 阶乘循环变为 0

algorithm - 找到 n,它的阶乘是阶乘的乘积

C OpenSSLRSA双重加密失败

c - 特里树,C 代码。效率低?