java.lang.Math类:
- Math 类包含了执行基本数值运算的方法,例如初等指数函数、对数函数、平方根以及三角函数。
- Math是一个工具类,提供的方法都是静态方法。
abs()方法:返回绝对值
示例:
package com.team.math;
public class Test {
public static void main(String[] args) {
System.out.println(Math.abs(-10));
System.out.println(Math.abs(2.02));
System.out.println(Math.abs(-2.22f));
}
}
运行输出:
10
2.02
2.22
public static double ceil(double a)方法:向上取整
返回大于或等于参数且等于数学整数的最小(最接近负无穷大)的 double 值。
示例:
package com.team.math;
public class Test {
public static void main(String[] args) {
System.out.println(Math.ceil(2.02));
System.out.println(Math.ceil(-2.02));
System.out.println(Math.ceil(2));
System.out.println(Math.ceil(-2));
}
}
运行输出:
3.0
-2.0
2.0
-2.0
public static double floor(double a)方法:向下取整
返回小于或等于给定参数且等于数学整数的最大(最接近正无穷)双精度浮点值。
示例:
package com.team.math;
public class Test {
public static void main(String[] args) {
System.out.println(Math.floor(2.02));
System.out.println(Math.floor(-2.02));
System.out.println(Math.floor(2));
System.out.println(Math.floor(-2));
}
}
运行输出:
2.0
-3.0
2.0
-2.0
round()方法:四舍五入
public static long round(double a)
public static int round(float a)
示例:
package com.team.math;
public class Test {
public static void main(String[] args) {
System.out.println(Math.round(2.52));
System.out.println(Math.round(-2.02));
System.out.println(Math.round(2));
System.out.println(Math.round(-2.52));
}
}
运行输出:
3
-2
2
-3
max()方法:取最大值
示例:
package com.team.math;
public class Test {
public static void main(String[] args) {
System.out.println(Math.max(2, 3));
System.out.println(Math.max(-2, -3));
System.out.println(Math.max(2.5, 3.3));
}
}
运行输出:
3
-2
3.3
min()方法:取最小值
示例:
package com.team.math;
public class Test {
public static void main(String[] args) {
System.out.println(Math.min(2, 3));
System.out.println(Math.min(-2, -3));
System.out.println(Math.min(2.5, 3.3));
}
}
运行输出:
2
-3
2.5
pow(double a, double b)方法:返回第一个参数的值的第二个参数次幂
示例:
package com.team.math;
public class Test {
public static void main(String[] args) {
// 2的3次方
System.out.println(Math.pow(2, 3));
// 2的-3次方
System.out.println(Math.pow(2, -3));
// 3的2次方
System.out.println(Math.pow(3, 2));
}
}
运行输出:
8.0
0.125
9.0
random()方法:取[0.0, 1.0)之间的随机数
示例:
package com.team.math;
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(Math.random());
}
}
}
运行输出:
0.8519787599085474
0.7059006339972921
0.5404980076316731
0.7954164458568925
0.5799128503916416
0.4690993453992277
0.7776165058075888
0.7736272204514367
0.6849099414826852
0.3269196357194003