问题
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