简体   繁体   中英

c function not returning result

I've very recently started to learn C, so I realize my question is very basic, but any help would be very much appreciated.

I'm trying to get the function fact to return the res value to main, but when I print out the result in main I just get 0. By inserting some print statements I can see that res is calculating correctly in the fact routine but the result is not returning correctly to main.

I'm sure I'm missing something very basic here.

Thanks

#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;
}

Your loop condition is n >= 0 , which means that res will be multipled by 0 before the function returns. Thus the result will always be 0.

You loop condition is wrong. The last run of while (n>=0) will have n=0 . Multiplying res by this will reset it to 0.

You can fix this by changing your loop to while (n > 1)

For future reference, you could investigate problems like this using a debugger (eg GDB or visual studio express). Or by adding printf statements to your code to trace the flow and see how the value of res changed through the program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM