快速解决方案 (Quick Solution)
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1) + myMin);
}
代码说明 (Code Explanation)
Math.random()
generates our random number between 0 and ≈ 0.9.Math.random()
生成介于0和≈0.9之间的随机数。Before multiplying it, it resolves the part between parenthesis
(myMax - myMin + 1)
because of the grouping operator( )
.在将其相乘之前,由于分组运算符
( )
,它会解析括号之间的部分(myMax - myMin + 1)
( )
。The result of that multiplication is followed by adding
myMin
and then "rounded" to the largest integer less than or equal to it (eg: 9.9 would result in 9)乘法的结果之后加上
myMin
,然后将“四舍五入”为小于或等于它的最大整数(例如:9.9将得出9)
If the values were myMin = 1, myMax= 10
, one result could be the following:
如果值为myMin = 1, myMax= 10
,则结果可能如下:
Math.random() = 0.8244326990411024
Math.random() = 0.8244326990411024
(myMax - myMin + 1) = 10 - 1 + 1 -> 10
(myMax - myMin + 1) = 10 - 1 + 1 -> 10
a * b = 8.244326990411024
a * b = 8.244326990411024
c + myMin = 9.244326990411024
c + myMin = 9.244326990411024
Math.floor(9.244326990411024) = 9
Math.floor(9.244326990411024) = 9
randomRange
should use both myMax
and myMin
, and return a random number in your range.
randomRange
应该同时使用myMax
和myMin
,并返回您范围内的随机数。
You cannot pass the test if you are only re-using the function ourRandomRange
inside your randomRange
formula. You need to write your own formula that uses the variables myMax
and myMin
. It will do the same job as using ourRandomRange
, but ensures that you have understood the principles of the Math.floor()
and Math.random()
functions.
如果仅在randomRange
公式中重新使用函数ourRandomRange
则无法通过测试。 您需要编写自己的使用变量myMax
和myMin
。 它将执行与使用ourRandomRange
相同的工作,但确保您已了解Math.floor()
和Math.random()
函数的原理。
翻译自: https://www.freecodecamp.org/news/generate-random-whole-numbers-within-a-range-javascript/