为什么整数的最大值和最小值之间的差异在算术上不正确?



为什么以下整数最大值和最小值的加减组合在算术上不正确?

public class Program
{
public static void main(String[] args) {
System.out.println(Integer.MIN_VALUE+" - "+Integer.MAX_VALUE+" = "+(long)(Integer.MIN_VALUE-Integer.MAX_VALUE));
System.out.println(Integer.MAX_VALUE+" - "+Integer.MIN_VALUE+" = "+(long)(Integer.MAX_VALUE-Integer.MIN_VALUE));
//the only correct result                     System.out.println(Integer.MAX_VALUE+" + "+Integer.MIN_VALUE+" = "+(long)(Integer.MAX_VALUE+Integer.MIN_VALUE));
}
}

输出

-2147483648 - 2147483647 = 1
2147483647 - -2147483648 = -1
2147483647 + -2147483648 = -1

强制转换为 long 不会阻止此处的整数溢出。您仍在添加和减去导致溢出的两个整数。因此,将操作中的任何一个操作数转换为 long,而不是将结果转换为 long。

Long result = Integer.MIN_VALUE+" - "+Integer.MAX_VALUE+" = "+(((long)Integer.MIN_VALUE)- Integer.MAX_VALUE)); // There is explicit type coersion. 

最新更新