java 18.数学工具类Math

数学工具类Math

java.lang.Math 类是数学相关的工具类,提供大量静态方法,完成与数学运算相关的操作,因为是lang包所以可以直接使用不需要导入。

获取绝对值

public static double abs(double num);

向上取整

public static double ceil(double num);

向下取整

public static double floor(double num);

四舍五入,不带小数点

public static double round(double num);

PI圆周率常数

public static final double PI = 3.14159265358979323846;

其他

使用(int) 10.99 强转(10),会舍弃所有小数位

实例代码

// 使用Arrays相关的api,将一个随机字符串中的所有字符升序排列,并倒序打印。
public class demo001 {
    public static void main(String[] args) {
        System.out.println(Math.abs(0));  //0
        System.out.println(Math.abs(1));  //1
        System.out.println(Math.abs(-1));  //1
        System.out.println(Math.ceil(3.001));  //4.0
        System.out.println(Math.ceil(3.999));  //4.0
        System.out.println(Math.floor(3.001));  //3.0
        System.out.println(Math.floor(3.999));  //3.0
        System.out.println(Math.round(3.001));  //3
        System.out.println(Math.round(3.999));  //4
        System.out.println("-----------------------");
        System.out.println(Math.ceil(-3.001));  //-3.0
        System.out.println(Math.ceil(-3.999));  //-3.0
        System.out.println(Math.floor(-3.001));  //-4.0
        System.out.println(Math.floor(-3.999));  //-4.0
        System.out.println(Math.round(-3.001));  //-3
        System.out.println(Math.round(-3.999));  //-4
    }
}

细心的同学会发现,ceilfloor传入的参数如果有负号,那么函数实现的效果正好相反

练习

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

// 计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?
public class demo001 {
    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) {
                count++;
            }
        }
        System.out.println("总共有:" + count + "个!");
    }
}

这里记录一个出错点

请添加图片描述

我一开始想练下刚学的几个函数,

通过abs取到绝对值10.8,再用floor向下取整10.0,然后再round拿掉小数点,得到10

然后IDEA报红线了,一看round是返回long型的,int接不住,所以...

但是不接收直接打印是OK的,可以得到期望的10

posted @ 2021-09-19 09:56  我是一言  阅读(239)  评论(0编辑  收藏  举报