java floor round ceil 使用

1、round使用System.out.println("Math.round=="+Math.round(11.46)+"=="+Math.round(11.50)+"=="+Math.round(11.76)+"=="+Math.round(-11.46)+"=="+Math.round(-11.76)+"=="+Math.round(-11.50));

----Math.round==11==12==12==-11==-12==-11

总结:Math.round()       
1)、  四舍五入的取整(小数点后第一位)大于五全部加,等于五正数加,小于五全不加。

2)、Math.round(Math.random()*(y-x))+x;   返回x~y的随机数,包含负数。

2、floor使用System.out.println("Math.floor=="+Math.floor(11.46)+"=="+Math.floor(11.50)+"=="+Math.floor(11.76)+"=="+Math.floor(-11.46)+"=="+Math.floor(-11.76)+"=="+Math.floor(-11.50));

-----Math.floor==11.0==11.0==11.0==-12.0==-12.0==-12.0

总结:Math.floor()(小于等于 x,且与 x 最接近的整数。)
其实返回值就是该数的整数位:
Math.floor(0.666)   -->  0
Math.floor(39.2783)   -->  39

所以我们可以使用Math.floor(Math.random())去获取你想要的一个范围内的整数。
如:现在要从1~52内取一个随机数:
首先Math.random()*52  //这样我们就能得到一个 >=0 且 <52的数
然后加1:Math.random()*52 + 1    //现在这个数就 >=1 且 <53
再使用Math.floor取整

最终: Math.floor(Math.random()*52 + 1)

这就能得到一个取值范围为1~52的随机整数了.

3、ceil使用System.out.println("Math.ceil=="+Math.ceil(11.46)+"=="+Math.ceil(11.50)+"=="+Math.ceil(11.76)+"=="+Math.ceil(-11.46)+"=="+Math.ceil(-11.76)+"=="+Math.ceil(-11.50));

-----Math.ceil==12.0==12.0==12.0==-11.0==-11.0==-11.0

总结:向上取整,如Math.cell(0.3)=1 、又如Math.ceil(Math.random()*10) 返回1~10

4、random使用

Math.random()       返回值是一个大于等于0,且小于1的随机数

Math.random()*N    返回值是一个大于等于0,且小于N的随机数

原文地址:https://www.cnblogs.com/523823-wu/p/9944177.html