java取整
- floor向下取证
用法:Math.floor(n);
Math.floor(1.4) // 1;
Math.floor(-1.4) // -2;
- round四舍五入
用法:Math.round(n) 约等于 Math.floor(n + 0.5)
注意:只对于浮点数来说存在四舍五入,浮点数转整型不存在。
Math.round(1.4)//1;
Math.round(1.6)//2;
Math.round(-1.4)//-1;
Math.round(-1.6)//-2;
//特殊(浮点型转整型)
int n = 11;
for(int i=0; i<(n/2); i++) //11/2为5.5,但是i为int,所以直接去电小数点后的值,等于5.
- ceil取不小于n的最小整数
用法:Math.ceil(n);
Math.ceil(1.4)//2;
Math.ceil(-1.4)//-1;
Math.ceil(1)//1;
- 也可以直接加(int)强转,直接省去小数点后的数。
java随机数
- random随机返回[0.0,1.0)之间的double类型的数
用法: 如取区间[a,b], 公式: int value = (int)(Math.random()*(b-a+1))+a;
注释:实际上这个方法还是内部先new了Random类生成了一个伪随机数生成器。
//求[0,100]
int n = (int) (Math.random() * 101) + 0
java求绝对值
- abs取绝对值
用法:Math.abs(n)
Math.abs(-6);//6
Math.abs(1-6);//5
java幂函数
- pow取幂指数
用法: Math.pow(a,b) a的b次方
Math.pow(x,2)//x的平方
Math.pow(x,3)//x的立方
java开根号
- sqrt开根号
用法: Math.sqrt(n),n的平方根
Math.sqrt(4)//2
Math.sqrt(9)//3
参考https://www.cnblogs.com/fireyjy/p/4720929.html