Math.abs(n):對int、long、float、double類型的數取絕對值
其中 int 類型的數取值范圍是 -2^31——2^31-1(-2147483648 ~ 2147483647)
舉例:
1 System.out.println(Math.abs(-2147483647)); 2 //輸出結果:2147483647 3 4 System.out.println(Math.abs(-2147483648)); 5 //輸出結果:-2147483648
為什么會得到這樣的結果呢?-2147483648沒有超過 int 的取值范圍,但是取絕對值后得到的還是負數?
查看了Math.abs()的注釋,看到了一段解釋:
Note that if the argument is equal to the value of Integer.MIN_VALUE
, the most negative representable int
value, the result is that same value, which is negative.
(百度翻譯:請注意,如果參數等於integer.min_value的值(最負的可表示int值),則結果是相同的值,這是負值。)
原來對於這個方法,如果是-2147483648不會進行處理,得到的還是負數