Math类的常用方法

1. Math.abs()

返回给定数字的绝对值。

public class MathExample {
    public static void main(String[] args) {
        int a = -10;
        double b = -12.34;
        
        System.out.println("Absolute value of " + a + ": " + Math.abs(a)); // 10
        System.out.println("Absolute value of " + b + ": " + Math.abs(b)); // 12.34
    }
}

2. Math.ceil()

返回大于或等于指定的浮点数的最小整数。

public class MathExample {
    public static void main(String[] args) {
        double num = 5.3;
        
        System.out.println("Ceiling value of " + num + ": " + Math.ceil(num)); // 6.0
    }
}

3. Math.floor()

返回小于或等于指定的浮点数的最大整数。

public class MathExample {
    public static void main(String[] args) {
        double num = 5.7;
        
        System.out.println("Floor value of " + num + ": " + Math.floor(num)); // 5.0
    }
}

4. Math.round()

返回四舍五入后的整数。

public class MathExample {
    public static void main(String[] args) {
        double num = 5.5;
        
        System.out.println("Rounded value of " + num + ": " + Math.round(num)); // 6
    }
}

5. Math.sqrt()

返回给定数字的平方根。

public class MathExample {
    public static void main(String[] args) {
        double num = 16.0;
        
        System.out.println("Square root of " + num + ": " + Math.sqrt(num)); // 4.0
    }
}

6. Math.pow()

返回第一个参数的第二个参数次方。

public class MathExample {
    public static void main(String[] args) {
        double base = 2;
        double exponent = 3;
        
        System.out.println(base + " raised to the power of " + exponent + ": " + Math.pow(base, exponent)); // 8.0
    }
}

7. Math.max()

返回两个数中的最大值。

public class MathExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        
        System.out.println("Max of " + a + " and " + b + ": " + Math.max(a, b)); // 20
    }
}

8. Math.min()

返回两个数中的最小值。

public class MathExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        
        System.out.println("Min of " + a + " and " + b + ": " + Math.min(a, b)); // 10
    }
}

9. Math.random()

返回一个介于0.0(包括)和1.0(不包括)之间的随机数。

public class MathExample {
    public static void main(String[] args) {
        double randomValue = Math.random();
        
        System.out.println("Random value: " + randomValue);
    }
}

10. Math.sin(), Math.cos(), Math.tan()

分别返回角度(以弧度为单位)的正弦、余弦和正切值。

public class MathExample {
    public static void main(String[] args) {
        double angle = Math.toRadians(30); // 30度转为弧度
        
        System.out.println("Sin(30): " + Math.sin(angle)); // 0.5
        System.out.println("Cos(30): " + Math.cos(angle)); // √3/2
        System.out.println("Tan(30): " + Math.tan(angle)); // 1/√3
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值