a<b 与 a-b<0 的区别
计算机中的不等式等价移项,需考虑数据的默认转换问题
【内容提要】下文记录的是,我们不留意 常忽视的极端情况:
且看如下小段代码:
public static void main(String[] args) { int maxValue = Integer.MAX_VALUE; int minValue = Integer.MIN_VALUE; if (maxValue < minValue) { System.out.println("maxValue < minValue"); } System.out.println("minValue = " + (minValue)); System.out.println("maxValue = " + (maxValue)); System.out.println("minValue - maxValue = " + (minValue - maxValue)); System.out.println("maxValue - minValue = " + (maxValue - minValue)); if (maxValue - minValue < 0) { System.out.println("maxValue - minValue < 0"); } }
执行结果:
1 minValue = -2147483648 2 maxValue = 2147483647 3 minValue - maxValue = 1 4 maxValue - minValue = -1 5 maxValue - minValue < 0 is True
这里出问题的原因是:默认转换所导致——
请看看这就清晰些:
1 public static void main(String[] args) { 2 int maxValue = Integer.MAX_VALUE; 3 int minValue = Integer.MIN_VALUE; 4 System.out.println("最大 Integer 值:Integer.MAX_VALUE = " + (maxValue)); 5 int a1 = maxValue+1; 6 System.out.println("Integer.MAX_VALUE + 1 = " + (a1) ); 7 int a2 = maxValue+2; 8 System.out.println("Integer.MAX_VALUE + 2 = " + (a2) ); 9 int a3 = maxValue+5; 10 System.out.println("Integer.MAX_VALUE + 5 = " + (a3) ); 11 12 System.out.println("------------"); 13 14 System.out.println("最小 Integer 值:Integer.MIN_VALUE = " + (minValue)); 15 int b1 = minValue-1; 16 System.out.println("Integer.MIN_VALUE - 1 = " + (b1) ); 17 int b2 = minValue-2; 18 System.out.println("Integer.MIN_VALUE - 2 = " + (b2) ); 19 int b3 = minValue-5; 20 System.out.println("Integer.MIN_VALUE - 5 = " + (b3) ); 21 }
【剧情反转】:极小值 反转 成为接近 极大值
执行结果:
1 最大 Integer 值:Integer.MAX_VALUE = 2147483647 2 Integer.MAX_VALUE + 1 = -2147483648 3 Integer.MAX_VALUE + 2 = -2147483647 4 Integer.MAX_VALUE + 5 = -2147483644 5 ------------ 6 最小 Integer 值:Integer.MIN_VALUE = -2147483648 7 Integer.MIN_VALUE - 1 = 2147483647 8 Integer.MIN_VALUE - 2 = 2147483646 9 Integer.MIN_VALUE - 5 = 2147483643
原因:追溯到计算机以二进制运算,首位作为符号位。正数的首位为0(符号位),负数的首位为1(符号位)
具体参见:[底层] 为什么Integer.MIN_VALUE-1会等于Integer.MAX_VALUE (可继续参看引用)