CodeGym /Java Blog /Toto sisi /Java Math.ceil() 方法
John Squirrels
等級 41
San Francisco

Java Math.ceil() 方法

在 Toto sisi 群組發布
在我們轉向 Java 中的 ceil 方法之前,最好熟悉一下數學中的 ceil 函數。

數學中的ceil函數是什麼?

“ceil 函數將十進制數轉換為直接最大整數。”
如果傳遞的數字已經是整數或整數,則相同的數字是上限值。但是,如果您將空值傳遞給數學中的 ceil 函數,您將得到一個“零”。

Java 中的 Math.ceil() 方法是什麼?

Java 提供了一種內置的方法來計算數學中的 ceil 函數。我們可以通過將“double”類型的參數傳遞給方法Math.ceil()來自由使用。在轉到用例之前,讓我們先看看一些邊界情況。
  • 如果參數“ double ”也是一個數學“整數”[例如:2.0 與 2 相同] -結果等於整數[即;2本身]
  • 如果參數 (let parameter = x)小於 0 但大於 -1 [ -1 > x < 0 ] -結果等於負零 [-0]
  • 如果參數為NaN、+0、-0 或 ∞ -結果與參數相同
  • 如果參數為“ null ”——與您得到零的數學 ceil 函數不同,這裡您將得到java.lang.NullPointerException

例子


class Main {

  public static void main(String[] args) {
  
    Double totalStudentsInClass = 25.0;
    Double flourWeightInKgs = 5.13;
    Double aPoundOfOxygenInLitres = 0.3977; 
    Double startingArrayIndexInJava = 0.0;
    Double aSelfDrivingCar = Double.NaN;
    Double numberOfStarsInTheSky = Double.POSITIVE_INFINITY;
    // For parameter  [ -1 > x < 0 ]
    Double x = -0.025;
    
    
    // using Math.ceil() method
    System.out.println("Total Students In Class = " + Math.ceil(totalStudentsInClass)); 
    System.out.println("Flour Weight In Kgs = " + Math.ceil(flourWeightInKgs));
    System.out.println("A Pound of Oxygen in Litres = " + Math.ceil(aPoundOfOxygenInLitres));
    System.out.println("Starting Array Index In Java = " + Math.ceil(startingArrayIndexInJava));
    System.out.println("A Self Driving Car = " + Math.ceil(aSelfDrivingCar));
    System.out.println("Number Of Stars In The Sky = " + Math.ceil(numberOfStarsInTheSky));
    System.out.println("Positive Zero = " + Math.ceil(+0.0));
    System.out.println("Negative Zero = " + Math.ceil(-0.0));
    System.out.println("x = " + x + " [ -1 > x < 0 ] = " + Math.ceil(-0.0));
  }

}

輸出

班級學生總數 = 25.0 麵粉重量(公斤)= 6.0 一磅氧氣(升)= 1.0 Java 中的起始數組索引 = 0.0 自動駕駛汽車 = NaN 天空中的星星數量 = 無窮大 正零 = 0.0 負零 = -0.0 x = -0.025 [ -1 > x < 0 ] = -0.0

結論

為了更好地掌握 java ceil 方法,我們建議您還具備數學上限函數的一些良好背景知識。擁有堅實的基礎有助於建立更堅實的基礎。儘管如此,您始終可以繼續學習、成長,並且一如既往地不要忘記練習!
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION