1. java.lang.Math
public final class Math {
}
2. 数学常量
@Test
public void constant() {
System.out.println("圆周率π=" + Math.PI);
System.out.println("自然对数底数e=" + Math.E);
}
3. 指数函数
@Test
public void exponential() {
System.out.println("算数平方根:" + Math.sqrt(4));
System.out.println("N次方:" + Math.pow(2, 10));
System.out.println("对数:" + Math.log10(201));
}
4. 取整函数
@Test
public void getInteger() {
/**
* Math.ceil(x) 向上取整,返回类型double
*/
System.out.println(Math.ceil(1.2) + ", " + Math.ceil(1.8) + ", " + Math.ceil(-1.2) + ", " + Math.ceil(-1.8));
/**
* Math.floor(x) 向下取整,返回类型double
*/
System.out.println(Math.floor(1.2) + ", " + Math.floor(1.8) + ", " + Math.floor(-1.2) + ", " + Math.floor(-1.8));
/**
* Math.round(x) 四舍五入取整,返回类型long
*/
System.out.println(Math.round(1.2) + ", " + Math.round(1.8) + ", " + Math.round(-1.2) + ", " + Math.round(-1.8));
// 取整,直接强转
int floor = (int) Math.floor(1.2);
System.out.println(floor);
}
打印结果:
2.0, 2.0, -1.0, -1.0
1.0, 1.0, -2.0, -2.0
1, 2, -1, -2
1
5. 最大最小值、绝对值
@Test
public void operate() {
System.out.println("最大值:" + Math.max(2, 3));
System.out.println("最小值:" + Math.min(2, 3));
System.out.println("绝对值:" + Math.abs(-1));
}
6. 随机数
Math.random() 生成的是区间在[0,1)
的随机小数 (double类型)
@Test
public void random() {
Stream.generate(() -> Math.random())
.limit(5)
.forEach(System.out::println);
}
生成[1,10]
的整数
@Test
public void random() {
Stream.generate(() -> (int) (Math.random() * 10) + 1)
.limit(5)
.forEach(System.out::println);
}
网友评论