简体   繁体   English

Math.random() 是如何工作的?

[英]How does Math.random() work like this?

So here we get a random number between 0 and 1 and round it down, so it always equals 0 right?所以在这里我们得到一个介于 0 和 1 之间的随机数并将其四舍五入,所以它总是等于 0,对吗?

var random = Math.floor(Math.random());

And then here we times it by 5. So surely 0 * 5 will always equal to 0?然后我们把它乘以 5。那么 0 * 5 肯定总是等于 0 吗?

var random = Math.floor(Math.random() * 5);

So how does it return a number between 1 and 5?那么它如何返回一个介于 1 和 5 之间的数字呢?

Thanks谢谢

The expression表达式

Math.floor(Math.random() * 5)

is evaluated by first calling Math.random() and then multiplying that result by 5. That will be a number between 0 and 5 (possibly equal to zero, but always less than 5).是通过首先调用Math.random()然后将该结果乘以 5 来计算的。这将是一个介于 0 和 5 之间的数字(可能等于 0,但始终小于 5)。

Only then will that result be passed to Math.floor() .只有这样,结果才会传递给Math.floor()

Parenthesized subexpressions are evaluated first, in general.通常,括号内的子表达式首先被评估。 In this case, it's a function call, but that's still a good "rule of thumb" to keep in mind.在这种情况下,它是一个函数调用,但这仍然是一个很好的“经验法则”,需要牢记。 "Work from the inside out", which is kind-of backwards from how you're supposed to use silverware at a fancy dinner. “由内而外工作”,这与您在豪华晚宴上使用银器的方式有点背道而驰。 I confess to never having figured out what to do with the utensils at the top of the plate however.我承认我从来没有想过如何处理盘子顶部的餐具。

Math.floor(Math.random() * 5)

.random() 生成 0 到 1 之间的随机数,.floor() 将数字向下舍入到最接近的整数。

var random = Math.round(Math.random() / (1/5))

这将使您的号码介于 1-5 之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM