数据类型相关问题?

作者站长头像
站长
· 阅读数 30

整笔记时发现了个挺奇怪的问题 (Java 版本是 17)

首先, int 类型的取值范围是 -2147483648 ~ 2147483647那么, 如果我定义一个这样的值, 在通过运算突破极值范围, 那他还是个 int 类型吗?于是我试着写了这样一段代码

public static void main(String[] args) {
    int num = 2147483647;
    int numGreater = num * 2;
    System.out.println(numGreater); // -2
}

这个问题没有什么实际的意义, 只是纯好奇有没有大佬知道, numGreater 的值为什么会等于 -2 ?

public static void main(String[] args) {
    int num = 2147483647;
    int numGreater = num + 1;
    System.out.println(numGreater); // -2147483648
}

好像只要在极限的边缘做运算得出来的结果都挺奇怪的

回复
1个回答
avatar
test
2024-06-21

muliplication expression *

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.

就是按照足够大的位数算一个精确结果,然后只取低位。

不同语言的规定会不太一样,所以要看语言自己的规定。

但是结果通常都是类似的,因为这样实现起来最方便。

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容