我目前正在学习微积分,并认为我会制作一个快速程序,它会给我阶乘 10 的结果。在测试它时,我注意到在第 5 次迭代后我得到了不正确的结果。但是,前 4 次迭代是正确的。

public class Factorial
{
    public static void main(String[] args)
    {

        int x = 1;
        int factorial;

        for(int n = 10; n!=1; n--)
        {

            factorial = n*(n-1);
            x = x * factorial;
            System.out.printf("%d ", x);

        }

    }//end of class main
}//end of class factorial

最佳答案

您超出了int类型的容量(2,147,483,647),因此您的结果将回绕到最小int值。尝试改用long

话虽如此,您当前使用的方法将无法得出正确的答案:实际上,您当前正在计算10! ^ 2

为什么使事情复杂化?您可以轻松地执行以下操作:

long x = 1L;

for(int n = 1; n < 10; n++)
{
    x *= n;
    System.out.println(x);
}

1个
2个
6
24
120
720
5040
40320
362880

它显示连续的阶乘,直到达到10!

另外,就像其他人提到的那样,如果您需要的值大于long可以支持的值,则应使用 BigInteger ,它支持任意精度。

10-07 19:32
查看更多