Math类和Random类

42 阅读1分钟

java.lang.Math提供了一系列静态方法用于科学计算,常用方法:

Math类

  • abs 取绝对值
  • acos,asin,atan,cos,sin,tan三角函数
  • sqrt 平方根
  • pow(double a, double b) a的b次幂
  • max(double a, double b) 取大值
  • min(double a, double b) 取小值
  • ceil(double a) 大于a的最小整数
  • floor(double a) 小于a的最大整数
  • random() 返回0.0 到 1.0 的随机数
  • long round(double a), 四舍五入取整数

public class Test {
    public static void main(String[] args) throws ParseException {
        System.out.println(Math.ceil(3.2));// 4.0
        System.out.println(Math.floor(3.9)); // 3.0
        System.out.println(Math.round(3.2)); // 3
        System.out.println(Math.round(3.8)); // 4
        System.out.println(Math.abs(-10)); // 10
        System.out.println(Math.sqrt(64)); // 8.0
        System.out.println(Math.pow(5, 2)); // 25.0
        System.out.println(Math.pow(2, 5)); // 32.0
        System.out.println(Math.PI);// 3.14125...
        System.out.println(Math.E); // 2.718...
        System.out.println(Math.random()); // [0,1)
    }
}

Random类

image.png

image.png

image.png