您好,欢迎访问一九零五行业门户网

使用Math.floor与Math.random取随机整数的方法详解_基础知识

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 且 然后加1:math.random()*52 + 1    //现在这个数就 >=1 且 再使用math.floor取整
最终: math.floor(math.random()*52 + 1)
这就能得到一个取值范围为1~52的随机整数了.
其它类似信息

推荐信息