Math.round()方法取整規則

刷題看到Math.round()題目,就知道又到了翻文檔的時候了

返回最接近參數的 long。結果將舍入爲整數:加上 1/2,對結果調用 floor 並將所得結果強制轉換爲 long 類型。換句話說,結果等於以下表達式的值:
(long)Math.floor(a + 0.5d)
特殊情況如下:
如果參數爲 NaN,那麼結果爲 0。
如果結果爲負無窮大或任何小於等於 Long.MIN_VALUE 的值,那麼結果等於 Long.MIN_VALUE 的值。
如果參數爲正無窮大或任何大於等於 Long.MAX_VALUE 的值,那麼結果等於 Long.MAX_VALUE 的值。

下面直接貼例子

System.out.println("1.4 round結果" + Math.round(1.4));
System.out.println("1.5 round結果" + Math.round(1.5)); 
System.out.println("1.6 round結果" + Math.round(1.6));
System.out.println("2.4 round結果" + Math.round(2.4));
System.out.println("2.5 round結果" + Math.round(2.5));
System.out.println("2.6 round結果" + Math.round(2.6));
System.out.println("-1.4 round結果" + Math.round(-1.4));
System.out.println("-1.5 round結果" + Math.round(-1.5));
System.out.println("-1.6 round結果" + Math.round(-1.6));
System.out.println("-2.4 round結果" + Math.round(-2.4));
System.out.println("-2.5 round結果" + Math.round(-2.5));
System.out.println("-2.6 round結果" + Math.round(-2.6));

運行結果爲

1.4 round結果1
1.5 round結果2
1.6 round結果2
2.4 round結果2
2.5 round結果3
2.6 round結果3
-1.4 round結果-1
-1.5 round結果-1
-1.6 round結果-2
-2.4 round結果-2
-2.5 round結果-2
-2.6 round結果-3

可以看出來,無論正數或者負數或者負數,運算規則相同,都是在給出數值的絕對值基礎上+0.5,然後向下取整

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章