Math数学类
219字小于1分钟
2025-09-23
Math数学类
全是静态方法,可以直接调用
绝对值
// 绝对值(abs)
int abs = Math.abs(-2);
System.out.println(abs); // 2
幂
// 幂(pow)
double pow = Math.pow(2, 4); // 2 的 4 次方
System.out.println(pow); // 16
向上取整
// 向上取整(ceil)
double ceil = Math.ceil(3.001);
System.out.println(ceil); // 4.0
向下取整
// 向下取整(floor)
double floor = Math.floor(3.001);
System.out.println(floor); // 3.0
四舍五入
// 四舍五入(round)
double round = Math.round(3.001);
System.out.println(round); // 3.0
开方
// 开方(sqrt)
double sqrt = Math.sqrt(9.0);
System.out.println(sqrt); // 3.0
随机数
// 随机数
// a = 5, b = 10(取5到10之间的随机数)
// 公式:(int)(a + Math.random() * (b - a + 1))
int a = 5;
int b = 10;
for (int i = 0; i < 10; i++) {
System.out.print((int)(a + Math.random() * (b - a + 1)) + " ");
}
最小值
// 最小值(min)
System.out.println(Math.min(2, 7)); // 2
最大值
// 最大值(max)
System.out.println(Math.max(2, 7)); // 7