java.math包中常用的方法

java.math包中常用的方法

1.Math.floor():向下取整(但结果是小数):

public class TestDemo1 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Math.floor(11.5));//11.0
        System.out.println(Math.floor(11.6));//11.0
        System.out.println(Math.floor(11.4));//11.0
        System.out.println(Math.floor(-11.5));//-12.0
        System.out.println(Math.floor(-11.6));//-12.0
        System.out.println(Math.floor(-11.4));//-12.0
    }
}

2.Math.abs():绝对值

public class TestDemo1 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Math.abs(11.5));//11.5
        System.out.println(Math.abs(11));//11
        System.out.println(Math.abs(-11.5));//11.5
        System.out.println(Math.abs(-11));//11
    }
}

3.Math.pow(a,b):幂函数,a的b次方;

public class TestDemo1 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Math.pow(2,3));//8.0
        System.out.println(Math.pow(2.0,3));//8.0
        System.out.println(Math.pow(2,3.0));//8.0
        System.out.println(Math.pow(2.0,3.0));//8.0
    }
}

4.Math.sqrt():算术平方根;(结果是double)

public class TestDemo1 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Math.sqrt(8));
        System.out.println(Math.sqrt(8.0));
        System.out.println(Math.sqrt(9));//3.0
        System.out.println(Math.sqrt(9.0));//3.0
    }
}

5.- Math.max():最大值;Math.min():最小值;

public class TestDemo1 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Math.max(2,5));//5
        System.out.println(Math.max(2.0,5));//5.0
        System.out.println(Math.max(2,5.0));//5.0
        System.out.println(Math.max(2.0,5.0));//5.0
        //min和max一样的道理
    }
}

6.Math.round()四舍五入

  • 规律;und(1.5) == 2;因为round对于正数是四舍五入的,对于负数:规律就是离谁近就是,比如-11.5,-11.4离-11最近就是-11,而-11.6离开-12近,就是-12;
public class TestDemo1 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Math.round(1.5));//2
        System.out.println(Math.round(1.6));//2
        System.out.println(Math.round(1.4));//1
        System.out.println(Math.round(-1.5));//-1
        System.out.println(Math.round(-1.6));//-2
        System.out.println(Math.round(-1.7));//-2
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45665172/article/details/110425564