要调用Math类中的方法,只需在代码中使用Math类的名称,并在方法名前加上类名 Math. 即可。不需要实例化Math类的对象,因为Math类中的方法都是静态的。以下是一个示例:
public class Main { public static void main(String[] args) { double x = 2.5; double y = -3.7; double absX = Math.abs(x); // 调用Math类中的abs()方法,返回x的绝对值 double absY = Math.abs(y); // 调用Math类中的abs()方法,返回y的绝对值 double maxXY = Math.max(x, y); // 调用Math类中的max()方法,返回x和y中的最大值 double sqrtX = Math.sqrt(x); // 调用Math类中的sqrt()方法,返回x的平方根 System.out.println("绝对值:" + absX + ", " + absY); System.out.println("最大值:" + maxXY); System.out.println("平方根:" + sqrtX); } }
输出结果:
绝对值:2.5, 3.7 最大值:2.5 平方根:1.5811388300841898