Skip to content

Math类的使用

Math 包含执行基本数字运算的方法,如指数,对数,平方根,三角函数。(在帮助文档中查找吧)

2. Math 类的常用方法

方法名说明
public static int abs(int a)返回参数的绝对值
public static double ceil(double a)返回大于或等于参数的最小double值,等于一个整数
public static double floor(double a)返回小于或等于参数的最大double值,等于一个整数
public static int round(float a)按照四舍五入返回最接近参数的int
public static int max(int a,int b)返回两个int值中的较大值
public static int min(int a,int b)返回两个int值中的较小值
public static double pow(double a,double b)返回 a 的 b 次幂的值
public static double random()返回值为double的正值,[0.0,1.0)

测试:

java
package Math的使用;

public class MathDemo {
    public static void main(String[] args) {
        System.out.println(Math.abs(88));  //输出结果为 88
        System.out.println(Math.abs(-88));  //输出结果为 88
        System.out.println("--------------------------");

        System.out.println(Math.max(50,60));  //输出结果为 60
        System.out.println(Math.max(80,70));  //输出结果为 80
        System.out.println("---------------------------");

        System.out.println(Math.floor(12.4));  //输出结果为 12.0
        System.out.println(Math.floor(13.6));  //输出结果为 13.0
        System.out.println("----------------------------");

        System.out.println(Math.min(20,30));  //输出结果为 20
        System.out.println(Math.min(50,40));  //输出结果为 40
        System.out.println("----------------------------");

        System.out.println(Math.pow(2.0,3.0));  //输出结果为 8.0
        System.out.println("----------------------");

        System.out.println(Math.random()*100+1);  //输出结果为 81.91695108466416 (1到100随机数)
        System.out.println("----------------------------");

        System.out.println(Math.round(12.4));  //输出结果为 12
        System.out.println(Math.round(12.6));  //输出结果为 13
        System.out.println("----------------------------");

        System.out.println(Math.ceil(12.4));  //输出结果为 13.0
        System.out.println(Math.ceil(12.6));  //输出结果为 13.0
        System.out.println("----------------------------");
    }
}