java - 在java中打印大的乘数

标签 java int multiplication primitive-types system.out

我正在做 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/

相关文章:

c++ - 使用按位运算符相乘

c - 将 Int 拆分为 3 个字节并在 C 中返回

java - 使用Mockito需要覆盖所有方法吗?

java - 为使用 jdbc 的应用程序编写测试用例

java - 从小程序上传文件到服务器

java - 从 long 到 int 的可能有损转换,JAVA

java - 使用 int 的位表示进行操作

c++ - 整数除法,还是 float 乘法?

python - 如何使用函数将列表相乘?

java - 在 Java 中为领域特定语言编写解析器