我正在做 AP Comp Sci 复习表,但编译时我不明白为什么
System.out.println(365 * 24 * 3600 * 1024 * 1024 * 1024);
答案是0。我知道int是32位,最大为2147483647,不能给你3386152216166400,但为什么它不会给出溢出异常错误或类似的错误?
最佳答案
来自Java Language Specification ,
The integer operators do not indicate overflow or underflow in any way.
这就是为什么你没有得到任何异常。
结果是specified by the language如下,
If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.
Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
Integer.MIN_VALUE - 1 == Integer.MAX_VALUE
这就是为什么你的结果为零。
关于java - 在java中打印大的乘数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48011441/