在第5次迭代后,因子循环结果不正确 [英] Factorial loop results are incorrect after the 5th iteration

查看:136
本文介绍了在第5次迭代后,因子循环结果不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently taking pre-calculus and thought that I would make a quick program that would give me the results of factorial 10. While testing it I noticed that I was getting incorrect results after the 5th iteration. However, the first 4 iterations are correct.

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

You're surpassing the capacity of the int type (2,147,483,647), so your result is wrapping back around to the minimum int value. Try using long instead.

话虽如此,您目前使用的方法不会导致正确回答:实际上,你目前正在计算 10! ^ 2

Having said the that, the method you are currently employing will not result in the correct answer: actually, you are currently computing 10! ^ 2.

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

Why complicate things? You could easily do something like this:

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!

which shows successive factorials until 10! is reached.

此外,正如其他人所提到的,如果你需要的值大于 long 可以支持你应该使用 BigInteger ,支持任意精度。

Also, as others have mentioned, if you need values bigger than what long can support you should use BigInteger, which supports arbitrary precision.

这篇关于在第5次迭代后,因子循环结果不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆