为什么有人会对 Math.random
结果调用 Math.floor
?我见过它像这样使用:
Math.floor(Math.random() * num);
有人可以解释一下吗?
最佳答案
Math.random
返回一个介于 0 和 1 之间的 float 。
Returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range.
将其乘以 n 得到一个介于 0(含)和 n(不含)之间的 float 。
Math.floor
然后用于将此 float 转换为介于 0 和 n - 1(含)之间的整数。
关于javascript - 为什么我要把 Math.floor 和 Math.random 结合起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8002820/