英文:
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*44 是int文字的乘法,因此执行int乘法,导致int值。在将结果分配给long变量之前,在这种情况下会溢出(因为结果大于Integer.MAX_VALUE)。因此,结果是不正确的。
将其更改为 49L*48*47*46*45*44 或 (long)49*48*47*46*45*44 以执行long乘法。
另一方面,在你的第一次计算中,你从一个值为1的long变量开始,然后在每次迭代中将该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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论