Java中的Math.abs()


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不會進行處理,得到的還是負數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM