Math.floor(Math.random()* 5 +1)的概念,真正的范围是什么,为什么? [英] Concept of Math.floor(Math.random() * 5 + 1), what is the true range and why?

查看:526
本文介绍了Math.floor(Math.random()* 5 +1)的概念,真正的范围是什么,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过将随机数(0到1之间)乘以5,我们将其设为0到5之间的随机数(例如3.1841). Math.floor()将这个数字四舍五入为整数,最后加1会将范围从0到4更改为1到5(最大为5).

By multiplying the random number (which is between 0 and 1) by 5, we make it a random number between 0 and 5 (for example, 3.1841). Math.floor() rounds this number down to a whole number, and adding 1 at the end changes the range from between 0 and 4 to between 1 and 5 (up to and including 5).

上面的解释使我感到困惑...我在下面的解释:

The explanation above confused me... my interpretation below:

-将5加到5的范围内 -但它以0开头(像数组一样?) -所以从技术上讲0-4 -加上一个,就变成1-5

--adding the 5 gives it a range of 5 numbers --but it starts with 0 (like an array?) --so it's technically 0 - 4 --and by adding the one, you make it 1 - 5

我对JS还是很陌生,甚至不知道这种问题在这里是否合适,但是到目前为止,这个站点很棒.谢谢您的帮助!

I am very new to JS, don't even know if this kind of question is appropriate here, but this site has been great so far. Thank you for any help!

推荐答案

来自

Math.random()函数返回一个浮点伪随机数,范围为[0,1),即从0(包括0)到但不包括1(排除).

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).

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

Here are two example randomly generated numbers:

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

因此,当我们将随机生成的数字乘以另一个数字时,它的范围是从0到小于所乘数字的最大值1(因为Math.floor()只是删除小数位而不是四舍五入(也就是说,用Math.floor() not 1处理时,0.999变为0).

Because of this, when we multiply our randomly generated number by another number, it will range from 0 to a maximum of 1 lower than the number being multiplied by (as Math.floor() simply removes the decimal places rather than rounding the number (that is to say, 0.999 becomes 0 when processed with Math.floor(), not 1)).

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

添加一个简单地将其抵消为您想要的值:

Adding one simply offsets this to the value you're after:

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

这篇关于Math.floor(Math.random()* 5 +1)的概念,真正的范围是什么,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆