java Math

发布时间 2023-11-26 22:06:26作者: _Elaina

package net.elaina.math;

public class Test1 {
    public static void main(String[] args) {
        //abs 获取参数绝对值
        //System.out.println(Math.abs(88));  //88
        //System.out.println(Math.abs(-88)); //88
        //bug:
        //以int类型为例,取值范围:-2147483648~2147483647
        //如果没有正数与负数对应,那么传递负数结果有误
        //-2147483648没有正数与之对应,所以abs结果产生bug
        //System.out.println(Math.abs(-2147483648)); //-2147483648
        //System.out.println(Math.absExact(-2147483648)); //报错

        //进一法,往数轴的正方向进一 ceil
        System.out.println(Math.ceil(12.34)); //13.0
        System.out.println(Math.ceil(12.54)); //13.0
        System.out.println(Math.ceil(-12.34)); //-12.0
        System.out.println(Math.ceil(-12.54)); //-12.0
        System.out.println("---------------------------------");

        //去尾法 round
        System.out.println(Math.round(12.34)); //12.0
        System.out.println(Math.floor(12.54)); //12.0
        System.out.println(Math.floor(-12.34)); //-13.0
        System.out.println(Math.floor(-12.54)); //-13.0
        System.out.println("---------------------------------");


        //四舍五入 round
        System.out.println(Math.round(12.34)); //12.0
        System.out.println(Math.round(12.54)); //13.0
        System.out.println(Math.round(-12.34)); //-12.0
        System.out.println(Math.round(-12.54)); //-13.0
        System.out.println("---------------------------------");


        //获取两个整数的较大值
        System.out.println(Math.max(20,30)); //30
        System.out.println(Math.min(20,30)); //20
        System.out.println("---------------------------------");

        //获取a的b次幂
        System.out.println(Math.pow(2,3)); //8.0
        //细节:
        //如果第二个参数 0~1之间的小数
        System.out.println(Math.pow(4,0.5)); // 2.0
        System.out.println(Math.pow(2,-2)); //0.25
        //建议:
        //第二个参数:一般传递大于等于1的正整数。
        System.out.println(Math.sqrt(4));  // 2.0 平方根
        System.out.println(Math.cbrt(8)); // 2.0 立方根
        System.out.println("---------------------------------");

        System.out.println(Math.random()); //随机数,[0.0,1.0]


    }
}