一、Math类
常用Math方法:
方法 | 意义 |
---|---|
Math.abs(x); | 取绝对值 |
Math.round(x); | 四舍五入返回值为long或int,原理是加上0.5再向下取整;//-1.6为-2,-1.5为-1 // 1.6为2,1.5为2 |
Math.sqrt(x); | √(x)、 x的二次方根 |
Math.cbrt(x); | 返回该数的立方根 |
Math.max(x, y); | 返回x、y中较大的那个数 |
Math.min(x, y); | 返回x、y中较小的那个数 |
Math.pow(x, y); | 返回 x的y次幂 |
Math.random(); | 随机返回[0,1)之间的无符号double值 |
Math.ceil(x); | 向上取整,返回最近的等于或大于这个数的整数值,但返回值类型为double |
Math.floor(y); | 向下取整,返回最近的等于或小于这个数的整数值,但返回值类型为double |
Math.signum(x); | 如果x大于0则返回1.0,小于0则返回-1.0,等于0则返回0 |
Math.exp(x); | e的x次幂 |
Math.scalb(x, y); | x*(2的y次幂) |
Math.hypot(x, y); | √(x²+y²) |
Math.log(x); | 以e为底的对数,即lnx |
Math.log10(100); | 以10为底的对数 |
Math.rint(x); | 返回最接近这个数的整数,如果刚好居中,则取偶数 |
Math.sin(α); | sin(α)的值 |
Math.cos(α); | cos(α)的值 |
Math.tan(α); | tan(α)的值 |
Math.PI | 兀、圆周率 |
Math.E | 自然对数e |
随机数
1、Math.random()
通过Math.random()方法可以产生0.0到1.0之间的double型随机数,但只要稍做处理即可产生任意范围的随机数;
int s=(int)num1+(int)(Math.random()*(num2-num1));//产生num1到num2之间的随机数[num1,num2)
2、Random类
Random random=new Random();
int number = random.nextInt(5);//生成0到5之间的随机数【0,5)