Java Math的floor、ceil、round方法

這幾個方法都位於java.lang包下的Math類中,都爲靜態方法。

ceil方法:

static double ceil(double a)

返回值爲double類型,返回的值大於或等於參數的double類型的值,並且等於某個整數(這麼說總感覺怪怪的)

floor方法:

static double floor(double a)

返回值同樣爲double類型,返回的值爲小於或等於參數的double類型的值,並且等於某個整數

round方法:

    //該方法爲重載方法
    static long round(double a)
    static int round(float a)

返回最接近參數的整數,該方法等同於Math.floor(a + 0.5)並將結果轉換爲long或int類型

public class MathTest {
    public static void main(String[] args) {
        double[] nums = {-0.6, -1.5, -1, 0.5, 1.2, 1.8};
        for(double n : nums) {
            test(n);
        }
    }

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

運行結果:

Math.ceil(-0.6)=-0.0
Math.floor(-0.6)=-1.0
Math.round(-0.6)=-1
Math.ceil(-1.5)=-1.0
Math.floor(-1.5)=-2.0
Math.round(-1.5)=-1
Math.ceil(-1.0)=-1.0
Math.floor(-1.0)=-1.0
Math.round(-1.0)=-1
Math.ceil(0.5)=1.0
Math.floor(0.5)=0.0
Math.round(0.5)=1
Math.ceil(1.2)=2.0
Math.floor(1.2)=1.0
Math.round(1.2)=1
Math.ceil(1.8)=2.0
Math.floor(1.8)=1.0
Math.round(1.8)=2

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