計算機中的不等式等價移項,需考慮數據的默認轉換問題
有多少人想罵人?
shuting(音:蝦挺 ,譯:關閉,消停,閉嘴)
且看如下小段代碼:
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 b = -2147483648 2 a = 2147483647 3 b - a = 1 4 a - b = -1 5 a - b < 0
這裏出問題的原因是:默認轉換所導致——
請看看這就清晰些:
1 public static void main(String[] args) { 2 int maxValue = Integer.MAX_VALUE; 3 int minValue = Integer.MIN_VALUE; 4 System.out.println("最大值: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.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.MAX_VALUE = 2147483647 2 Integer.MAX_VALUE + 1 ——>-2147483648 3 Integer.MAX_VALUE + 2 ——>-2147483647 4 Integer.MAX_VALUE + 5 ——>-2147483644 5 ------------ 6 最小值: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 (可繼續參看引用)