天天看點

Java中Math類的幾種常用方法

public class MathDemo {
    public static void main(String args[]){
        /**
         * abs求絕對值
         */
        System.out.println(Math.abs(-));    //10.4
        System.out.println(Math.abs());     //10.1

        /**
         * ceil天花闆的意思,就是傳回大的值,注意一些特殊值
         */
        System.out.println(Math.ceil(-));   //-10.0
        System.out.println(Math.ceil());    //11.0
        System.out.println(Math.ceil(-));    //-0.0
        System.out.println(Math.ceil());     //0.0
        System.out.println(Math.ceil(-));    //-0.0

        /**
         * floor地闆的意思,就是傳回小的值
         */
        System.out.println(Math.floor(-));  //-11.0
        System.out.println(Math.floor());   //10.0
        System.out.println(Math.floor(-));   //-1.0
        System.out.println(Math.floor());    //0.0
        System.out.println(Math.floor(-));   //-0.0

        /**
         * max 兩個中傳回大的值,min和它相反,就不舉例了
         */
        System.out.println(Math.max(-, -));   //-10.0
        System.out.println(Math.max(, ));     //10.7
        System.out.println(Math.max(, -));    //0.0

        /**
         * random 取得一個大于或者等于0.0小于不等于1.0的随機數
         */
        System.out.println(Math.random());  //0.08417657924317234
        System.out.println(Math.random());  //0.43527904004403717

        /**
         * rint 四舍五入,傳回double值
         * 注意.5的時候會取偶數
         */
        System.out.println(Math.rint());    //10.0
        System.out.println(Math.rint());    //11.0
        System.out.println(Math.rint());    //12.0
        System.out.println(Math.rint());    //10.0
        System.out.println(Math.rint());   //11.0
        System.out.println(Math.rint(-));   //-10.0
        System.out.println(Math.rint(-));   //-12.0
        System.out.println(Math.rint(-));  //-11.0
        System.out.println(Math.rint(-));   //-11.0
        System.out.println(Math.rint(-));   //-10.0

        /**
         * round 四舍五入,float時傳回int值,double時傳回long值
         */
        System.out.println(Math.round());   //10
        System.out.println(Math.round());   //11
        System.out.println(Math.round());   //11
        System.out.println(Math.round());  //11
        System.out.println(Math.round(-));  //-10
        System.out.println(Math.round(-)); //-11
        System.out.println(Math.round(-));  //-11
        System.out.println(Math.round(-));  //-10
    }
}