Java 的 Math 类位于 java.lang 包中,提供了许多用于执行基本数学运算的静态方法。这些方法可以直接通过类名调用,而不需要创建 Math 类的实例。以下是一些常用的 Math 类方法及其示例:
1. 基本算术运算
-
Math.abs(double a):返回参数的绝对值。double negativeNumber = -10.5; double absoluteValue = Math.abs(negativeNumber); System.out.println(absoluteValue); // 输出 10.5 -
Math.ceil(double a):返回大于或等于参数的最小整数(向上取整)。double decimalNumber = 10.2; int ceilingValue = (int) Math.ceil(decimalNumber); System.out.println(ceilingValue); // 输出 11 -
Math.floor(double a):返回小于或等于参数的最大整数(向下取整)。double decimalNumber = 10.8; int floorValue = (int) Math.floor(decimalNumber); System.out.println(floorValue); // 输出 10 -
Math.round(double a):返回最接近参数的整数(四舍五入)。double decimalNumber = 10.5; int roundedValue = Math.round(decimalNumber); System.out.println(roundedValue); // 输出 11 -
Math.max(double a, double b)和Math.min(double a, double b):返回两个参数中的最大值和最小值。double num1 = 5.5; double num2 = 3.3; double maxValue = Math.max(num1, num2); double minValue = Math.min(num1, num2); System.out.println("Max: " + maxValue + ", Min: " + minValue); // 输出 Max: 5.5, Min: 3.3
2. 三角函数
-
Math.sin(double a):返回参数的正弦值。double angleInRadians = Math.PI / 2; // 90度 double sineValue = Math.sin(angleInRadians); System.out.println(sineValue); // 输出 1.0 -
Math.cos(double a):返回参数的余弦值。double angleInRadians = 0; // 0度 double cosineValue = Math.cos(angleInRadians); System.out.println(cosineValue); // 输出 1.0 -
Math.tan(double a):返回参数的正切值。double angleInRadians = Math.PI / 4; // 45度 double tangentValue = Math.tan(angleInRadians); System.out.println(tangentValue); // 输出 1.0 -
Math.toRadians(double angdeg):将角度转换为弧度。double degrees = 90; double radians = Math.toRadians(degrees); System.out.println(radians); // 输出 1.5707963267948966 (即 PI/2) -
Math.toDegrees(double angrad):将弧度转换为角度。double radians = Math.PI / 2; // 90度 double degrees = Math.toDegrees(radians); System.out.println(degrees); // 输出 90.0
3. 指数和对数函数
-
Math.exp(double a):返回e的a次幂。double exponent = 1; double result = Math.exp(exponent); System.out.println(result); // 输出 2.718281828459045 (即 e) -
Math.log(double a):返回参数的自然对数(底为e)。double value = Math.E; // e 的值 double logValue = Math.log(value); System.out.println(logValue); // 输出 1.0 -
Math.log10(double a):返回参数的以 10 为底的对数。double value = 100; double log10Value = Math.log10(value); System.out.println(log10Value); // 输出 2.0 -
Math.sqrt(double a):返回参数的平方根。double value = 16; double squareRoot = Math.sqrt(value); System.out.println(squareRoot); // 输出 4.0 -
Math.pow(double a, double b):返回a的b次幂。double base = 2; double exponent = 3; double result = Math.pow(base, exponent); System.out.println(result); // 输出 8.0
4. 随机数
-
Math.random():返回一个大于等于0.0且小于1.0的双精度浮点数。double randomValue = Math.random(); System.out.println(randomValue); // 输出一个介于 0.0 和 1.0 之间的随机数
5. 其他常用方法
-
Math.PI:返回圆周率π的值。double piValue = Math.PI; System.out.println(piValue); // 输出 3.141592653589793 -
Math.E:返回自然对数的底数e的值。double eValue = Math.E; System.out.println(eValue); // 输出 2.718281828459045
这些是 Java Math 类中一些最常用的方法。通过这些方法,你可以执行各种数学运算,满足大多数编程需求。