为什么有人会在 Math.random
的结果上调用 Math.floor
?我看到过它被这样使用:
Math.floor(Math.random() * num);
可以有人解释一下吗?
为什么有人会在 Math.random
的结果上调用 Math.floor
?我看到过它被这样使用:
Math.floor(Math.random() * num);
可以有人解释一下吗?
Math.random
返回一个在0到1之间的 浮点数。
返回一个范围在 [0, 1) 的浮点伪随机数,即从 0(包括)到 1(不包括)之间的数,然后您可以根据自己的需求进行缩放。
将此乘以n会得到一个在 0(包括)到 n(不包括)之间的浮点数。
然后使用 Math.floor
将该浮点数转换为介于 0 和 n - 1(包含)之间的整数。
Math.random()
是否真的包括 0
?我在一个 while
循环中运行了 1 百万次,它没有生成过 0
:/ 我问这个问题是因为某些计算,如 Math.ceil(Math.random() * 10)
比 Math.floor(Math.random() * 10 + 1)
更简洁。 - oldboyMath.floor(Math.random() * num);
将Math.floor(Math.Random() * num)
拆分成各个部分并解释每个部分,你会得到以下内容:0.38548569372
这样的值。
Math.random() * num
会给你一个0到num之间(包括0但不包括num)的随机小数。所以如果num是10,它可能会给你3.8548569372
。
Math.floor(Math.random() * num))
会给你一个0到num之间(包括0但不包括num)的随机整数。所以它可能会给你3
。Math.floor()
返回比输入小的最大整数。Math.ceil()
返回比输入大的最小整数。Math.round()
检查输入值并返回最接近它的下一个较小或较大的整数,具体取决于哪个更接近。将来,MDN 网站 是所有这些类型问题的绝佳参考。 - jfriend00Math.random()
会返回一个长长的、随机的小数。通常我们会将这个小数乘上10、100、1000等来得到一个随机的整数。但由于这样的小数太长,为了得到一个绝对的整数,你需要使用Math.floor()
函数将它向下取整。
Math.floor
与Math.random
结合使用?num
)的值。因此,Math.floor只是强制使其成为整数。num
)乘以->获得3.85-> Math.floor(3.85)-> 3。num
是MAX + 1。将num
设置为5只会生成1-4的数字!这是用于获取0到(max-1)之间整数随机数的函数。
另一方面,可以使用| 0
更快地实现:
const randomInt = Math.random() * num | 0;
| 0
是对0进行二进制或运算,JavaScript规范有效地表示在执行|
操作之前将结果转换为整数。请注意,| 0
与Math.floor
不同。 | 0
四舍五入到0,而Math.floor
向下取整。 | 0 Math.floor
------+------+------------
2.5 | 2 | 2
1.5 | 1 | 1
0.5 | 0 | 0
-0.5 | 0 | -1
-1.5 | -1 | -2
-2.5 | -2 | -3
value = maybeValue || defaultValue
以及 value = condition && expression
,两者看起来都像巫术,但你会习惯的。 |0
也类似。你只需要查找它的含义,现在它就是你知识的一部分了。 - gmanvar num = Math.floor(Math.random() * 1000); // e.g. 885
var flNum = Math.random() * 1000; //e.g. 885.9936205333221
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
Math.random()
返回类似于 0.8747230430599302
的值,范围在 [0,1) 之间。
我们使用 .floor
将其向下舍入到最近的整数。例如:
Math.random()*5 == 2.5889716914389282
这将生成一个介于 [0,5) 之间的数字。
Math.floor(Math.random()*5) == 2 //在这种情况下
生成一个介于 [0,4] 之间的数字。
Math.random()
是否真的包括 0
?我在一个 while
循环中运行了 1 百万次,它没有生成过 0
:/ 我问这个问题的原因是因为某些计算,如 Math.ceil(Math.random() * 10)
比 Math.floor(Math.random() * 10 + 1)
更简洁。 - oldboy