這篇文章給大家分享的是有關Java中Math.round函數的示例分析的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
1.代碼如下:
public class TestMathRound { public static void main(String[] args) { System.out.println("小數點后第一位=5"); System.out.println("正數:Math.round(11.5)=" + Math.round(11.5));//12 System.out.println("負數:Math.round(-11.5)=" + Math.round(-11.5));//-11 System.out.println(); System.out.println("小數點后第一位<5"); System.out.println("正數:Math.round(11.46)=" + Math.round(11.46));//11 System.out.println("負數:Math.round(-11.46)=" + Math.round(-11.46));//-11 System.out.println(); System.out.println("小數點后第一位>5"); System.out.println("正數:Math.round(11.68)=" + Math.round(11.68));//12 System.out.println("負數:Math.round(-11.68)=" + Math.round(-11.68));//-12 } }
2.結果如下,可以自己運行。
3.本來以為是四舍五入,取最靠近的整數,查了網上說有四舍六入五成雙,最后還不如看源碼。源碼如下:
public static long round(double a) { if (a != 0x1.fffffffffffffp-2) // greatest double value less than 0.5 return (long)floor(a + 0.5d); else return 0; }
我們看到round函數會默認加0.5,之后調用floor函數,然后返回。floor函數可以理解為向下取整。
4.綜上,Math.round函數是默認加上0.5之后,向下取整。
感謝各位的閱讀!關于“Java中Math.round函數的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。