数学类
Math类
Java 中的 Math 类是 java.lang 包的一部分,提供了一系列的静态方法来实现数学运算,包括基本的算术运算、三角函数、指数和对数函数等。由于 Math 是一个 final 类,你不能继承它或实例化它。
以下是 Math 类的一些常用方法:
-
基本算术运算:
abs: 绝对值min: 最小值max: 最大值sqrt: 平方根pow: 指数(幂次方)
-
三角函数:
sin: 正弦cos: 余弦tan: 正切asin: 反正弦(返回值在 -π/2 到 π/2 之间)acos: 反余弦(返回值在 0 到 π 之间)atan: 反正切atan2: 从 xy 平面上某点 (x, y) 到原点 (0, 0) 的角度的反正切
-
指数和对数函数:
exp: e 的指数log: 自然对数(底数为 e)log10: 以 10 为底的对数
-
圆周率和 Euler 数:
PI: 圆周率的近似值E: Euler 数的近似值
-
角度和弧度的转换:
toRadians: 将角度转换为弧度toDegrees: 将弧度转换为角度
-
随机数生成:
random: 返回一个 [0.0, 1.0) 范围内的随机浮点数
-
舍入操作:
round: 对浮点数进行四舍五入
-
符号操作:
signum: 返回参数的符号函数
示例代码:
public class MathExample {
public static void main(String[] args) {
// 基本算术运算
int resultAbs = Math.abs(-5);
double resultSqrt = Math.sqrt(16);
double resultPow = Math.pow(2, 3);
// 三角函数
double resultSin = Math.sin(Math.toRadians(30));
double resultCos = Math.cos(Math.toRadians(60));
// 指数和对数函数
double resultExp = Math.exp(1);
double resultLog = Math.log(10);
double resultLog10 = Math.log10(100);
// 随机数生成
double randomDouble = Math.random();
// 舍入操作
int resultRound = Math.round(3.7);
System.out.println("abs(-5): " + resultAbs);
System.out.println("sqrt(16): " + resultSqrt);
System.out.println("pow(2, 3): " + resultPow);
System.out.println("sin(30°): " + resultSin);
System.out.println("cos(60°): " + resultCos);
System.out.println("exp(1): " + resultExp);
System.out.println("log(10): " + resultLog);
System.out.println("log10(100): " + resultLog10);
System.out.println("random(): " + randomDouble);
System.out.println("round(3.7): " + resultRound);
}
}
Math 类是 Java 程序中进行数学运算的基础工具,它的静态方法可以满足大多数数学计算的需求。

浙公网安备 33010602011771号