关于math:Math类的三个方法比较-floor-ceil-round

3次阅读

共计 995 个字符,预计需要花费 3 分钟才能阅读完成。

public class Test {public static void main(String[] args) {
        double d1 = 3.4,    d2 = 3.6;   // 负数
        double d3 = -3.4,   d4 = -3.6;  // 正数

        float f1 = 4.4F,    f2 = 4.6F;  // 负数
        float f3 = -4.4F,   f4 = -4.6F; // 正数

        //floor() 办法只能接管 double 类型, 返回 double 类型
        // 向下取整, 返回小于参数的最大整数
        System.out.println(Math.floor(d1));//3.0
        System.out.println(Math.floor(d2));//3.0
        System.out.println(Math.floor(d3));//-4.0
        System.out.println(Math.floor(d4));//-4.0


        //ceil() 办法只能接管 double 类型, 返回 double 类型
        // 向上取整, 返回大于参数的最小整数
        System.out.println(Math.ceil(d1));//4.0
        System.out.println(Math.ceil(d2));//4.0
        System.out.println(Math.ceil(d3));//-3.0
        System.out.println(Math.ceil(d4));//-3.0


        //round() 办法能够接管 double 类型, 返回 long 类型
        // 示意“四舍五入”,算法为 Math.floor(x+0.5),行将参数加上 0.5 后再向下取整
        System.out.println(Math.round(d1));//3
        System.out.println(Math.round(d2));//4
        System.out.println(Math.round(d3));//-3
        System.out.println(Math.round(d4));//-4

        //round() 办法能够接管 float 类型, 返回 int 类型
        System.out.println(Math.round(f1));//4
        System.out.println(Math.round(f2));//5
        System.out.println(Math.round(f3));//-4
        System.out.println(Math.round(f4));//-5
    }
}
正文完
 0