为什么我的递归阶乘方法总是返回0? [英] Why does my recursive factorial method always return 0?
问题描述
我创建了一个递归方法来计算数字的fasctial,但是,它总是返回0,我不知道为什么.我在下面提供了我的代码:
I have created a recursive method to calculate the facortial of a number, however, it is always returning 0, and I can not see why. I have provided my code below:
public class projectTwenty {
public static void main(String [] args) {
int factorialAns = factorial(100);
System.out.println(factorialAns);
}
private static int factorial(int n) {
if (n == 0) {
return 1;
}else {
return (n * factorial(n-1));
}
}
}
我尝试过更改函数的调用方式以及返回值的方式,到目前为止,还没有碰到运气. 我还在Google/StackOverflow上搜索了类似的方法/问题,但仍未找到解决方案.
I have tried changing the way in which the function is called and how values are returned, no luck so far. I have also searched Google/StackOverflow for similar methods/questions and am yet to find a solution.
推荐答案
因为100阶乘的位数太多,导致整数类型溢出.您可以尝试使用较小的值,但效果会更好.
Because 100 factorial has so much digits that it causes an overflow on the integer type. You can try it on a smaller values and it will work much better.
如果要实际计算大阶乘,可以在Java中使用BigInteger类.
In case you want to actually calculate big factorials you can use the BigInteger class in java.
这篇关于为什么我的递归阶乘方法总是返回0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!