c函数不返回结果

use*_*961 2 c return function

我最近开始学习C,所以我意识到我的问题非常基础,但是非常感谢任何帮助.

我试图获得函数事实将res值返回到main,但是当我在main中打印出结果时我得到0.通过插入一些print语句我可以看到res在事实例程中正确计算但是结果未正确返回到main.

我确定我在这里遗漏了一些非常基本的东西.

谢谢

#include <stdio.h>

unsigned long fact (int n){
    unsigned long res = 1;

    while ( n >= 0 )
    {
        res *= n;
        n--;
    }

    return res;
}

int main (void){
    int n;
    unsigned long res;

    printf("Insert number:\n");
    scanf("%d", &n );

    res = fact (n);

    printf("The factorial number is %lu", res);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 8

你的循环条件是n >= 0,这意味着res在函数返回之前将乘以0.因此结果将始终为0.


sim*_*onc 7

你循环条件错了.最后一次运行while (n>=0)将有n=0.乘以res此将重置为0.

您可以通过将循环更改为来解决此问题 while (n > 1)

为了将来参考,您可以使用调试器(例如GDB或visual studio express)调查此类问题.或者通过printf在代码中添加语句来跟踪流程并查看res通过程序更改的值的方式.

  • +1但是`while(n> 1)`会更好,因为乘以1是没用的. (3认同)