文章目录
1. 基本介绍
- Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
2. 方法一览(均为静态方法)

3. Math 类常见方法应用案例
public class MathMethod {
public static void main(String[] args) {
int abs = Math.abs(-9);
System.out.println(abs);
double pow = Math.pow(2, 4);
System.out.println(pow);
double ceil = Math.ceil(3.9);
System.out.println(ceil);
double floor = Math.floor(4.001);
System.out.println(floor);
long round = Math.round(5.51);
System.out.println(round);
double sqrt = Math.sqrt(9.0);
System.out.println(sqrt);
}
}

3. random 求随机数
random
:求随机数,返回的是 0 <= x < 1
之间的一个随机小数
- 思考题:请写出获取
a-b
之间的一个随机整数,a,b
均为整数 ,比如 a = 2, b=7;
, 即返回一个数的范围在: 2 <= x <= 7
- 解读:
Math.random() * (b-a) 返回的就是 0 <= 数 <= b-a
(1) (int)(a) <= x <= (int)(a + Math.random() * (b-a + 1) )
(2) 使用具体的数介绍 a = 2 b = 7
(int)(a + Math.random() * (b-a +1) ) = (int)( 2 + Math.random()*6)
Math.random()*6 返回的是 0 <= x < 6 之间的小数
2 + Math.random()*6 返回的就是 2<= x < 8 之间的小数
(int)(2 + Math.random()*6) = 2 <= x <= 7
(3) 公式就是 (int)(a + Math.random() * (b-a +1) )
for (int i = 0; i < 10; i++) {
System.out.println((int) (2 + Math.random() * (7 - 2 + 1)));
}

int min = Math.min(1, 9);
int max = Math.max(45, 90);
System.out.println("min=" + min);
System.out.println("max=" + max);
