为什么以下Integer的最大值和最小值的加法或减法组合算术不正确?
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
答案 0 :(得分:0)
转换为long不会阻止此处的整数溢出。您仍在添加和减去导致溢出的两个整数。因此,将操作中的任何一个操作数强制转换为long,而不是将结果转换为long。
Long result = Integer.MIN_VALUE+" - "+Integer.MAX_VALUE+" = "+(((long)Integer.MIN_VALUE)- Integer.MAX_VALUE)); // There is explicit type coersion.