问题描述
我试图获取数字 66 的阶乘值,但是我的方法导致输出 0 .但是,每当我尝试获取阶乘 5 时,它都会向我输出 120 .谁能告诉我为什么?
public static int factorial(int n)
{
if (n == 1)
return n;
return n * factorial(n - 1);
}
当然-阶乘变得非常大,非常快.您正在迅速溢出int 非常的边界...在某些时候,您将乘以足够多的因子以使溢出变为0,这将使该值永远保持为0. /p>
根据Google的快速搜索,阶乘为66为5.44344939×10 -远远超过了int
甚至是long
或decimal
的处理能力.您可能会得到double
来处理它-您将损失大量的精度,这也会非常迅速地积累,但至少不会溢出...
I'm trying to get the factorial value of number 66, but my method resulting me an output 0. But whenever I try to get the factorial of 5, it is resulting me an output 120. Could anyone please tell me why?
public static int factorial(int n)
{
if (n == 1)
return n;
return n * factorial(n - 1);
}
Sure - factorials get very big, very fast. You're overflowing the bounds of int very quickly... and at some point you'll have multiplied by enough factors to get an overflow to 0, which will then keep the value at 0 forever.
According to a quick Google search, 66 factorial is 5.44344939 × 10 - which is considerably more than int
can handle, or even long
or decimal
. You could get double
to handle it - you'd lose a huge amount of precision, and that would accumulate really quickly too, but at least it wouldn't overflow...
这篇关于阶乘方法导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!