数学工具类Math以及练习

Math类是数学相关的工具类,里面提供了大量的静态方法,完成与数学运算的相关操作

public static double obs(double num);  获取绝对值,有多种重载。

public sttaic double ceil(double num);  向上取整

public sttaic double floor(double num);  向下取整

public sttaic long round(double num);  四舍五入

Math.PI 代表近似圆周率的常量(double)

    public static void main(String[] args) {
        //获取绝对值
        System.out.println(Math.abs(11.56));
        System.out.println(Math.abs(0));
        System.out.println(Math.abs(-11.56));
        System.out.println("=============");
        //向上取整
        System.out.println(Math.ceil(3.5));
        System.out.println(Math.ceil(3.1));
        System.out.println(Math.ceil(0));
        System.out.println("=============");
        //向下取整
        System.out.println(Math.floor(3.9));
        System.out.println(Math.floor(3.1));
        System.out.println(Math.floor(0));
        System.out.println("=============");
        //四舍五入
        System.out.println(Math.round(3.5));
        System.out.println(Math.round(3.4));
        //PI
        System.out.println(Math.PI);
    }

运行结果:

 

 

练习

计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?

    public static void main(String[] args) {
        int count = 0;
        double min = -10.8;
        double max = 5.9;
        for (int i = (int) min; i < max; i++) {
            int abs = Math.abs(i);
            if (abs>6 || abs<2.1){
                System.out.println(i);
                count++;
            }
        }
        System.out.println("共有:"+count+"个");
    }

运行结果:

 

 

posted @ 2022-06-30 15:12  xjw12345  阅读(58)  评论(0)    收藏  举报