当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Math.floor(Math.random()*3+1)

Math.floor(Math.random()*3+1)

2019年03月30日  | 移动技术网IT编程  | 我要评论

math.random():获取0~1随机数

math.floor() method rounds a number downwards to the nearest integer, and returns the result. (小于等于 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的随机整数了.

-----------------------------------------------------------------------------------------------------------------------------------------

math.(random/round/cell/floor)随机数的用法


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

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

 

math.round()         四舍五入的取整
math.ceil()            向上取整,如math.cell(0.3)=1 、又如math.ceil(math.random()*10) 返回1~10
math.floor()           向下取整,如math.floor(0.3)=0、又如math.floor(math.random()*10)返回0~9

 

引申:
math.round(math.random()*15)+5;   返回5~20随机数

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网