gpt4 book ai didi

javascript - Math.floor(Math.random() * 5 + 1)的概念,真实范围是多少,为什么?

转载 作者:数据小太阳 更新时间:2023-10-29 05:12:41 31 4
gpt4 key购买 nike

通过将随机数(介于 0 和 1 之间)乘以 5,我们使其成为介于 0 和 5 之间的随机数(例如,3.1841)。 Math.floor() 将该数字向下舍入为整数,并在末尾添加 1 将范围从 0 到 4 更改为 1 到 5(最多并包括 5)。

上面的解释让我很困惑……我的解释如下:

--加上 5 得到 5 个数字的范围--但它以 0 开头(像数组?)--所以它在技术上是 0 - 4--加上一个,就变成了 1 - 5

我是 JS 的新手,甚至不知道这种问题在这里是否合适,但这个网站到目前为止一直很棒。感谢您的帮助!

最佳答案

来自Mozilla Developer Networks' documentationMath.random() 上:

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive).

下面是两个随机生成的数字示例:

Math.random() // 0.011153860716149211
Math.random() // 0.9729151880834252

正因为如此,当我们将随机生成的数字与另一个数字相乘时,它的范围从 0 到最大 1 小于被乘以的数字(如 Math.floor() 简单删除小数位而不是舍入数字(也就是说,0.999 在使用 Math.floor() 处理时变为 0,不是 1)。

Math.floor(0.011153860716149211 * 5) // 0
Math.floor(0.9729151880834252 * 5) // 4

加 1 只是将其抵消为您想要的值:

Math.floor(0.011153860716149211 * 5) + 1 // 1
Math.floor(0.9729151880834252 * 5) + 1 // 5

关于javascript - Math.floor(Math.random() * 5 + 1)的概念,真实范围是多少,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21483667/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com