开发者

strange behaviour of the java

hello I have some question about java, why 开发者_Go百科the following code return strange value?

System.out.println("Strange " + (20 * 232792560)/20);

why do I recieve 18044195?


Because (20 * 232792560) overflows the range of an int, and wraps round the number range several times to become 360883904. That is then divided by 20 to give you the result that you see.

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.)


Because (20 * 232792560) will perform integer based multiplication and the result is obviously out of int's range, hence the value will be truncated.


Because 20 * 232792560 does not fit in 4 bytes (integer value).

So you got:

20 * 232792560 = 360883904; // because of int overflow
360883904 / 20 = 18044195; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜