Math.floor(Math.random()) +1 实际上做了什么

Math.floor(Math.random()) what does +1 actually do?

本文关键字:Math 什么 实际上 floor random      更新时间:2023-09-26

当你Math.floor(Math.random()*10)+1它应该从我的理解中选择一个 1-10 之间的随机数。

但是,当我将+1更改为更高或更低的任何数字时,1我得到相同的结果。这是为什么呢?+1到底是什么意思?

随机数生成器生成的值范围为 0.0 <<p>= n <1.0。如果你想要一个介于 1 和 1 之间的数字,则需要应用+1偏移量。

通常您可以使用:

Math.floor(Math.random() * N) + M

这将生成介于 M 和 M + N - 1 之间的值。

演示小提琴

Math.random()生成一个介于 0 和 1 之间的随机数。

因此,Math.random()*10生成一个介于 0 和 10 之间的随机数,并(Math.random()*10)+1一个介于 1 和 11 之间的数字。

Math.floor() 删除此数字的小数,并使其成为 0 到 10 之间的整数。

您可以在此处看到逻辑的顺序进展

整数介于 1 和 10 之间

  • Math.random() 生成介于 0 和 1 之间的数字(有许多小数位)。

等:math.random() [随机返回 : 0.19157057767733932]
这个数字仍然有很多小数位

要获得随机整数,您需要将随机生成的数字乘以 10。


math.random()*10 =[随机返回 : 2.9757621488533914]

  • 由于该数字仍然有许多小数位,因此请使用 floor() 方法将数字向下/最接近的整数四舍五入,这将给 u 一个介于 0 和 9 之间的值。然后,您可以添加 1 使其成为介于 1 和 10 之间的数字。

等:
数学地板(0.6)   [返回 0 ]
数学地板(0.6)+ 1 [返回 1  ]

基本:

(random() >= 0)总是true

(random() < 1)总是true

(Math.floor(random()) == 0)总是true

最大:

(Math.floor(random() * 10) >= 0)总是true

(Math.floor(random() * 10) < 10)总是true

最低:

(Math.floor(random() * 10) + 1 >= 1)总是true

(Math.floor(random() * 10) + 1 < 11)总是true

最大回合数:

(Math.round(random() * 10, 0) >= 0)总是true

(Math.round(random() * 10, 0) <= 10)总是true