use*_*011 3 java math integer-overflow
为什么这段代码返回错误的值?
int i=Integer.MAX_VALUE+1;
long l=Integer.MAX_VALUE+1;
System.out.println(l);
System.out.println(i);
Run Code Online (Sandbox Code Playgroud)
当你向Integer.MAX_VALUE它添加1 溢出并包裹到Integer.MIN_VALUE.
这是因为Java使用二进制补码来表示整数.4位示例:
0000 : 0
0001 : 1
...
0111 : 7 (max value)
1000 : -8 (min value)
...
1110 : -2
1111 : -1
Run Code Online (Sandbox Code Playgroud)
因此,当你将1加到0111(最大)时,它会变为1000最小值.将此想法扩展到32位,它的工作方式相同.
至于你为什么long也显示不正确的结果,这是因为它在ints 上执行加法然后隐式转换为long.你需要这样做:
long l = (long) Integer.MAX_VALUE + 1
System.out.println(l); // now prints the correct value
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1730 次 |
| 最近记录: |