Math.random和Math.floor取随机数总结

来源:互联网 发布:java system类 编辑:程序博客网 时间:2024/06/05 09:41

1.Math.random();  //返回一个介于[0,1)之间的随机数

比如像产生一个介于 [0,50)的随机数:Math.random()*50;

但问题在于这样通常会产生小数,这时通过Math.floor();进行解决

2.Math.floor();   will take a decimal number,and round down to the nearest whole number,也就是说是向下取整

比如Math.floor(Math.random()*50);会产生[0,50)间的整数

练习:从1~66之间取一个随机整数

①Math.random()*66                 //随机得到一个>=0且<66的数

Math.random()*66 +1           //随机得到一个>=1且<67的数

③Math.floor(Math.random()*66 +1);   //取整得到[1,67)之间的整数即[1,66]之间的整数

拓展:

Math.round();  //四舍五入地取整

Math.ceil();       //向上取整,例如Math.ceil(Math.random()*10);返回的是1~10之间的整数 

Math.floor();    //向下取整,例如Math.floor(Math.random()*10);返回的是0~9之间的整数 

Math.round(Math.random()*(y-x))+x;   //返回x~y的随机整数