[英]strange behaviour of the java
hello I have some question about java, why the following code return strange value? 你好,我对Java有疑问,为什么以下代码返回奇怪的值?
System.out.println("Strange " + (20 * 232792560)/20);
why do I recieve 18044195
? 为什么我会收到
18044195
?
Because (20 * 232792560)
overflows the range of an int
, and wraps round the number range several times to become 360883904
. 因为
(20 * 232792560)
溢出了一个int
的范围,并且将数字范围环绕数次而变成360883904
。 That is then divided by 20
to give you the result that you see. 然后将其除以
20
即可得到所看到的结果。
If you want the correct result, then you need to do: 如果想要正确的结果,则需要执行以下操作:
System.out.println("Strange " + (20 * 232792560L) / 20);
(Marking a literal with an L
means that the constant maths will be done with long
, rather than with int
, so this will no longer overflow.) (用
L
标记文字,这意味着常量数学将使用long
而不是int
,因此不会再溢出。)
由于(20 * 232792560)
将执行基于整数的乘法,并且结果显然超出int
的范围,因此该值将被截断。
Because 20 * 232792560
does not fit in 4 bytes (integer value). 因为
20 * 232792560
不适合4个字节(整数值)。
So you got: 所以你得到:
20 * 232792560 = 360883904; // because of int overflow
360883904 / 20 = 18044195;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.