Math 的 floor,round 和 ceil 方法實例比較

知識點

函數 概念
ceil() 返回大於等於( >= )給定參數的的最小整數,類型爲雙精度浮點型。
floor() 返回小於等於(<=)給定參數的最大整數 。
round() 它表示四捨五入,算法爲 Math.floor(x+0.5),即將原來的數字加上 0.5 後再向下取整,所以,Math.round(11.5) 的結果爲12,Math.round(-11.5) 的結果爲-11。

實例

public class Main {   
  public static void main(String[] args) {   
    double[] nums = { 1.4, 1.5, 1.6, -1.4, -1.5, -1.6 };   
    for (double num : nums) {   
      test(num);   
    }   
  }   

  private static void test(double num) {   
    System.out.println("Math.floor(" + num + ")=" + Math.floor(num));   
    System.out.println("Math.round(" + num + ")=" + Math.round(num));   
    System.out.println("Math.ceil(" + num + ")=" + Math.ceil(num));   
  }   
}

運行結果

Math.floor(1.4)=1.0
Math.round(1.4)=1
Math.ceil(1.4)=2.0
Math.floor(1.5)=1.0
Math.round(1.5)=2
Math.ceil(1.5)=2.0
Math.floor(1.6)=1.0
Math.round(1.6)=2
Math.ceil(1.6)=2.0
Math.floor(-1.4)=-2.0
Math.round(-1.4)=-1
Math.ceil(-1.4)=-1.0
Math.floor(-1.5)=-2.0
Math.round(-1.5)=-1
Math.ceil(-1.5)=-1.0
Math.floor(-1.6)=-2.0
Math.round(-1.6)=-2
Math.ceil(-1.6)=-1.0

微信公衆號:IT小天地
關注可瞭解更多計算機相關知識。問題或建議,請公衆號留言;

發佈了240 篇原創文章 · 獲贊 370 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章