简介:
Math类在java.lang包中,其包含许多用来进行科学计算的静态类方法,这些方法可以直接通过类名调用,另外,Math类还有两个静态常量E和PI,下面介绍Math类的常用方法。
常用方法:
幂运算:double d=Math.pow(double a,double b);
绝对值:double d=Math.abs(double a);
两数求最大值:double d=Math.max(double x,double y);
两数求最大值:double d=Math.min(double x,double y);
返回一个[0,1)之间的double类型的随机数:double d=Math.random();
向上取整:int d=Math.ceil(double a);
向下取整:int d=Math.floor(double a);
返回最接近a的取整,若居中则取偶数:int d=Math.rint(double a);
四舍五入取整:int d=Math.round(double a);
角度转弧度 a180r/PI:double d=Math.toDegrees(double a);
弧度转角度 a/180rPI:double d=Math.toRadians(double a);
返回√(x2+y2):double d=Math.hypot(double x,double y);
返回√a,平方根:double d=Math.sqrt(double a);
返回3√a立方根:double d=Math.cbrt(double a);
返回比a大一点点的浮点数:double d=Math.nextUp(double a);
返回比a小一点点的浮点数:double d=Math.nextDown(double a);
返回(a,b)/(b,a)之间与a相邻的浮点数:double d=Math.nextAfter(double a,double b);
测试代码如下:
/**
* 测试Math类
* @author ZXL
*
*/
public class T04 {
public static void main(String[] args) {
//两个静态常量
System.out.println("PI:"+Math.PI);
System.out.println("E:"+Math.E);
//Math常用方法
System.out.println("幂运算:"+Math.pow(2,4)); //16.0
System.out.println("绝对值:"+Math.abs(-23.2)); //23.2
System.out.println("两数最大值:"+Math.max(100, 2)); //100
System.out.println("两数最大值:"+Math.min(100, 2)); //2
System.out.println("随机数:"+((int)Math.random()*6+1));
System.out.println("向上取整:"+Math.ceil(2.9)); //3.0
System.out.println("向下取整:"+Math.floor(2.9)); //2.0
System.out.println("最接近取整:"+Math.rint(2.9)); //3.0
System.out.println("四舍五入取整:"+Math.round(2.9)); //3
System.out.println("平方根:"+Math.sqrt(4)); //2.0
}
}