C递归函数计算阶乘 [英] C recursive function to calculate Factorial
问题描述
我刚刚开始学习C编程,并认为我将从计算数字阶乘的一个非常基本的问题开始.我的代码一直输出正确的值,直到阶乘13为止,然后在输入> 13时给出错误的答案.我的代码是:
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;
}
当我输入13时,它返回1932053504而不是预期的6227020800
When i input 13 it returns 1932053504 instead of the expected 6227020800
推荐答案
您可能在平台上溢出了LONG_MAX值,这导致了未定义的行为.您可以使用 unsigned long (或 unsigned long long ),但是它们也不会保存更长的时间.
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.
您的选择在这里受到限制.您可以使用支持任意大整数的库,例如 GNU GMP .否则,您必须像GMP一样自己实现它.
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.
另一方面,
else if (dig=1)
不是您想要的.应该是
else if ( dig == 1 )
或者您可以在此处简单地使用 else {...}
,除非您打算检查负数.
Or you can simply use else {...}
here unless you intend to check against negative numbers.
这篇关于C递归函数计算阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!