C recursive function to calculate Factorial

吃可爱长大的小学妹 提交于 2021-02-11 12:15:26

问题


Im just beginning to learn C programming and figured i would start out at a pretty basic problem of calculating the factorial of a number. My code outputs the correct value up until the factorial of 13 and then gives me the wrong answer for when the input is >13. My code is:

#include<stdio.h>
long int factorial(int);

int main()

{
    int num;
    long int fact;
    printf("Please type the number you want factoralized: ");
    scanf("%d",&num);

    fact = factorial(num);
    printf("%d",fact);
    return 0;
}
long int factorial(int dig)
{
    long int facto;
    if (dig>1)
        facto = dig * factorial(dig-1);
    else if (dig=1)
        facto = 1;
    return facto;
}

When i input 13 it returns 1932053504 instead of the expected 6227020800


回答1:


You are probably overflowing the LONG_MAX value on your platform which leads to undefined behaviour. You can use unsigned long (or unsigned long long) but they wouldn't hold for much longer either.

Your options are limited here. You could use libraries, such as GNU GMP that support arbitrarily large integers. Otherwise, you'll have to implement it yourself similar to GMP.

On another note,

else if (dig=1)

is not what you want. It should be

else if ( dig == 1 )

Or you can simply use else {...} here unless you intend to check against negative numbers.



来源:https://stackoverflow.com/questions/26876765/c-recursive-function-to-calculate-factorial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!