1. Math.abs()
返回给定数字的绝对值。
public class MathExample {
public static void main(String[] args) {
int a = -10;
double b = -12.34;
System.out.println("Absolute value of " + a + ": " + Math.abs(a)); // 10
System.out.println("Absolute value of " + b + ": " + Math.abs(b)); // 12.34
}
}
2. Math.ceil()
返回大于或等于指定的浮点数的最小整数。
public class MathExample {
public static void main(String[] args) {
double num = 5.3;
System.out.println("Ceiling value of " + num + ": " + Math.ceil(num)); // 6.0
}
}
3. Math.floor()
返回小于或等于指定的浮点数的最大整数。
public class MathExample {
public static void main(String[] args) {
double num = 5.7;
System.out.println("Floor value of " + num + ": " + Math.floor(num)); // 5.0
}
}
4. Math.round()
返回四舍五入后的整数。
public class MathExample {
public static void main(String[] args) {
double num = 5.5;
System.out.println("Rounded value of " + num + ": " + Math.round(num)); // 6
}
}
5. Math.sqrt()
返回给定数字的平方根。
public class MathExample {
public static void main(String[] args) {
double num = 16.0;
System.out.println("Square root of " + num + ": " + Math.sqrt(num)); // 4.0
}
}
6. Math.pow()
返回第一个参数的第二个参数次方。
public class MathExample {
public static void main(String[] args) {
double base = 2;
double exponent = 3;
System.out.println(base + " raised to the power of " + exponent + ": " + Math.pow(base, exponent)); // 8.0
}
}
7. Math.max()
返回两个数中的最大值。
public class MathExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Max of " + a + " and " + b + ": " + Math.max(a, b)); // 20
}
}
8. Math.min()
返回两个数中的最小值。
public class MathExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Min of " + a + " and " + b + ": " + Math.min(a, b)); // 10
}
}
9. Math.random()
返回一个介于0.0(包括)和1.0(不包括)之间的随机数。
public class MathExample {
public static void main(String[] args) {
double randomValue = Math.random();
System.out.println("Random value: " + randomValue);
}
}
10. Math.sin()
, Math.cos()
, Math.tan()
分别返回角度(以弧度为单位)的正弦、余弦和正切值。
public class MathExample {
public static void main(String[] args) {
double angle = Math.toRadians(30); // 30度转为弧度
System.out.println("Sin(30): " + Math.sin(angle)); // 0.5
System.out.println("Cos(30): " + Math.cos(angle)); // √3/2
System.out.println("Tan(30): " + Math.tan(angle)); // 1/√3
}
}