Java 的 Math
类提供了许多用于数学运算的方法。以下是一些常用的方法:
常用方法
-
基本运算
Math.abs(int a)
:返回绝对值。Math.max(int a, int b)
:返回较大值。Math.min(int a, int b)
:返回较小值。
-
指数运算
Math.pow(double a, double b)
:返回 ( a^b )。Math.sqrt(double a)
:返回平方根。
-
对数运算
Math.log(double a)
:返回自然对数(以 ( e ) 为底)。Math.log10(double a)
:返回以 10 为底的对数。
-
三角函数
Math.sin(double angle)
:返回角度的正弦值。Math.cos(double angle)
:返回角度的余弦值。Math.tan(double angle)
:返回角度的正切值。
-
反三角函数
Math.asin(double a)
:返回反正弦(弧度)。Math.acos(double a)
:返回反余弦(弧度)。Math.atan(double a)
:返回反正切(弧度)。
-
取整
Math.ceil(double a)
:向上取整。Math.floor(double a)
:向下取整。Math.round(double a)
:四舍五入。
-
随机数
Math.random()
:返回 [0.0, 1.0) 之间的随机数。
示例代码
public class MathExample {
public static void main(String[] args) {
System.out.println(Math.abs(-5)); // 5
System.out.println(Math.max(10, 20)); // 20
System.out.println(Math.sqrt(16)); // 4.0
System.out.println(Math.pow(2, 3)); // 8.0
System.out.println(Math.sin(Math.PI / 2)); // 1.0
System.out.println(Math.random()); // Random number
}
}
Math
类的方法都是静态的,因此可以直接通过类名调用,无需创建对象。