在Java中计算乘积,使用术语与’for’循环,结果不同。

huangapple go评论113阅读模式
英文:

Calculate product in Java, term vs. a 'for' loop, different results

问题

考虑:

    long y = 1;
    for (int i = 49; i > 43; i--) {
        y*= i;
    }

    long x = 49*48*47*46*45*44; // = 1478412928
    long y                      // = 10068347520

为什么结果不同,尽管计算方式都是偶数?

是否有解释?

英文:

Consider:

    long y = 1;
    for (int i = 49; i > 43; i--) {
        y*= i;
    }

    long x = 49*48*47*46*45*44; // = 1478412928
    long y                      // = 10068347520

Why are the results different although the calculation is even?

Is there an explanation?

答案1

得分: 4

49*48*47*46*45*44int文字的乘法,因此执行int乘法,导致int值。在将结果分配给long变量之前,在这种情况下会溢出(因为结果大于Integer.MAX_VALUE)。因此,结果是不正确的。

将其更改为 49L*48*47*46*45*44(long)49*48*47*46*45*44 以执行long乘法。

另一方面,在你的第一次计算中,你从一个值为1long变量开始,然后在每次迭代中将该long与一个int相乘,执行long乘法,因此没有溢出。

英文:

49*48*47*46*45*44 is a multiplication of int literals, and therefore performs int multiplications resulting in an int value. It overflows in this case (since the result is larger than Integer.MAX_VALUE) before you assign the result to the long variable. Hence the result is incorrect.

Change it to 49L*48*47*46*45*44 or (long)49*48*47*46*45*44 to perform long multiplication.

In your first calculation, on the other hand, you begin with a long variable whose value is 1, and the loop multiplies that long with an int in each iteration, performing long multiplication, so there's no overflow.

huangapple
  • 本文由 发表于 2020年8月18日 16:20:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63464571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定