Java中的 Math
类
Math
类提供了一系列用于执行常见数学运算的静态方法。这些方法包括基本的算术运算、指数运算、三角函数、取整、舍入等操作。下面详细讲解 Math
类的常用方法和使用。
1. 常用算术运算:
1.1 加法和减法:
int sum = Math.addExact(5, 7); // 加法
int difference = Math.subtractExact(10, 3); // 减法
1.2 乘法和除法:
int product = Math.multiplyExact(4, 5); // 乘法
double quotient = Math.floorDiv(10, 3); // 整除,返回商的整数部分
1.3 取余:
int remainder = Math.floorMod(10, 3); // 取余,返回余数
2. 指数运算:
double power = Math.pow(2, 3); // 2的3次方
double exponential = Math.exp(1.0); // e的1次方,即自然对数的底
double logarithm = Math.log(10.0); // 10的自然对数
3. 三角函数:
double sine = Math.sin(Math.toRadians(30)); // 正弦函数,参数是弧度
double cosine = Math.cos(Math.toRadians(45)); // 余弦函数,参数是弧度
double tangent = Math.tan(Math.toRadians(60)); // 正切函数,参数是弧度
4. 取整操作:
4.1 向下取整:
double floorValue = Math.floor(5.8); // 向下取整,返回不大于参数的最大整数
4.2 向上取整:
double ceilValue = Math.ceil(5.2); // 向上取整,返回不小于参数的最小整数
4.3 四舍五入:
long roundValue = Math.round(5.5); // 四舍五入,返回最接近参数的 long
5. 随机数生成:
double randomValue = Math.random(); // 生成一个[0, 1)之间的随机数
6. 常数:
double pi = Math.PI; // 圆周率
double e = Math.E; // 自然对数的底
7. 特殊值处理:
double positiveInfinity = Double.POSITIVE_INFINITY; // 正无穷大
double negativeInfinity = Double.NEGATIVE_INFINITY; // 负无穷大
double nan = Double.NaN; // 非数值
8. 注意事项:
Math
类中的方法都是静态方法,直接通过类名调用。- 在进行三角函数计算时,参数通常是弧度而非角度,可以通过
Math.toRadians()
将角度转换为弧度。
9. 使用示例:
public class MathExample {
public static void main(String[] args) {
// 常用算术运算
int sum = Math.addExact(5, 7);
int difference = Math.subtractExact(10, 3);
int product = Math.multiplyExact(4, 5);
double quotient = Math.floorDiv(10, 3);
int remainder = Math.floorMod(10, 3);
// 指数运算
double power = Math.pow(2, 3);
double exponential = Math.exp(1.0);
double logarithm = Math.log(10.0);
// 三角函数
double sine = Math.sin(Math.toRadians(30));
double cosine = Math.cos(Math.toRadians(45));
double tangent = Math.tan(Math.toRadians(60));
// 取整操作
double floorValue = Math.floor(5.8);
double ceilValue = Math.ceil(5.2);
long roundValue = Math.round(5.5);
// 随机数生成
double randomValue = Math.random();
// 常数
double pi = Math.PI;
double e = Math.E;
// 特殊值处理
double positiveInfinity = Double.POSITIVE_INFINITY;
double negativeInfinity = Double.NEGATIVE_INFINITY;
double nan = Double.NaN;
}
}