常用类Math,方法有很多,这里只取部分常用方法,有具体需求请查阅api文档
Math类的方法基本都是static
//Math类的常用方法
//abs() 求绝对值
int abs = Math.abs(-10);
System.out.println("求绝对值 "+abs); //输出 10
//pow() 求幂
double pow = Math.pow(2,3);
System.out.println("求幂 " + pow); //输出 8.0
//ceil() 向上取整
double ceil = Math.ceil(-3.0001);
System.out.println("向上取整 "+ ceil); //输出 -3.0
//floor() 向下取整
double floor = Math.floor(-3.00001);
System.out.println("向下取整 "+floor); //输出 -4.0
//round() 四舍五入
double round = Math.round(3.14159);
System.out.println("四舍五入 "+round); //输出3.0
//sqrt() 求开方
double sqrt = Math.sqrt(9.0); //3.0
System.out.println("求开方 "+sqrt);
//random() 取随机数 0< Math.random <1
for (int i = 0; i < 10; i++) {
System.out.println(Math.random());
}
//求任意两个整数之间的随机小数
int a3 = 2;
int a4 = 7;
for (int i = 0; i < 5; i++) {
System.out.println((int)(a3+Math.random()*(a4-a3+1)));
}
//max()求两个数的最大值
System.out.println(Math.max(20,19));
//min()求两个数的最小值
System.out.println(Math.min(21,22));
输出结果
求绝对值 10
求幂 8.0
向上取整 -3.0
向下取整 -4.0
四舍五入 3.0
求开方 3.0
0.7511483681784578
0.19041690193352445
0.23497897087215558
0.5007258348326712
0.97314571790342
0.09015675261264466
0.7900711476821841
0.2491896409048726
0.7824457661898273
0.3472833200392761
4
7
4
7
7
20
21