java數(shù)學工具類Math詳解(round方法)
數(shù)學工具類Math,供大家參考,具體內容如下
1. 概述
java.util.Math類是數(shù)學相關的工具類,里面提供了大量的靜態(tài)方法,完成與數(shù)學運算相關的操作。
2. 基本的方法
public static double abs(double num);獲取絕對值。有多種重載,absolutely絕對地 public static double ceil(double num);向上取整,ceil是天花板的意思 public static double floor(double num);向下取整,floor是地板的意思 public static long round(double num);四舍六入五成雙(看下面代碼的注釋),round有大約,完整的意思
3. 四種方法一起通過代碼演示一遍
public class MathMethod { public static void main(String[] args) { //abs方法,取絕對值 System.out.println(Math.abs(3.14)); //3.14 System.out.println(Math.abs(0)); //0 System.out.println(Math.abs(-2.2)); //2.2 System.out.println("---------------------"); //ceil方法,向上取整,往大的靠 System.out.println(Math.ceil(3.2)); //4.0 System.out.println(Math.ceil(3.8)); //4.0 System.out.println(Math.ceil(-3.2)); //-3.0 System.out.println(Math.ceil(-3.8)); //-3.0 System.out.println("---------------------"); //floor方法,向下取整,往小的靠 System.out.println(Math.floor(3.2)); //3.0 System.out.println(Math.floor(3.8)); //3.0 System.out.println(Math.floor(-3.2)); //-4.0 System.out.println(Math.floor(-3.8)); //-4.0 System.out.println("---------------------"); //【注意,面試高頻】round方法,四舍 六入 五成雙 //先看看四舍六入,如果出現(xiàn)負數(shù),先轉成正數(shù),再四舍六入,最后加上負號 System.out.println(Math.round(3.4)); //3 System.out.println(Math.round(3.6)); //4 System.out.println(Math.round(-3.4)); //-3 System.out.println(Math.round(-3.6)); //-4 //五成雙是什么意思呢?當出現(xiàn)0.5結尾的時候,就給它再加上+0.5,5不就成雙了 //接著再對相加的結果進行floor運算 System.out.println(Math.round(-2.5)); //-2 System.out.println(Math.floor(-2.5 + 0.5)); //與Math.round(-2.5)結果一致 System.out.println(Math.round(2.5)); //3 System.out.println(Math.floor(2.5 + 0.5)); //與Math.round(2.5)結果一致 } }
4. 圓周率Math.PI
在Math類的源碼中,我們可以看到,它自定義的圓周率 PI = 3.14159265358979323846
以后的計算如果需要用到PI,盡量用已經(jīng)定義好的圓周率,非常精確
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
IDEA利用jclasslib 修改class文件的實現(xiàn)
這篇文章主要介紹了IDEA利用jclasslib 修改class文件的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02Java Swing實現(xiàn)JTable檢測單元格數(shù)據(jù)變更事件的方法示例
這篇文章主要介紹了Java Swing實現(xiàn)JTable檢測單元格數(shù)據(jù)變更事件的方法,結合完整實例形式分析了Swing實現(xiàn)JTable檢測單元格數(shù)據(jù)變更事件過程中出現(xiàn)的問題與相關解決方法,需要的朋友可以參考下2017-11-11springboot的logging.group日志分組方法源碼流程解析
這篇文章主要為大家介紹了springboot的logging.group日志分組方法源碼流程解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12Java零基礎教程之Windows下安裝、啟動Tomcat服務器方法圖解(免安裝版)
這篇文章主要介紹了Windows系統(tǒng)下安裝、啟動、注冊服務、停止 Tomcat操作的所有方法,本文通過圖文并茂的方式給大家介紹的非常詳細,感興趣的朋友一起看看吧2016-09-09