如何使用JavaScript Math.floor生成范围内的随机整数-已解决

快速解决方案 (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 ,则结果可能如下:

  1. Math.random() = 0.8244326990411024

    Math.random() = 0.8244326990411024

  2. (myMax - myMin + 1) = 10 - 1 + 1 -> 10

    (myMax - myMin + 1) = 10 - 1 + 1 -> 10

  3. a * b =  8.244326990411024

    a * b = 8.244326990411024

  4. c + myMin = 9.244326990411024

    c + myMin = 9.244326990411024

  5. 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应该同时使用myMaxmyMin ,并返回您范围内的随机数。

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则无法通过测试。 您需要编写自己的使用变量myMaxmyMin 。 它将执行与使用ourRandomRange相同的工作,但确保您已了解Math.floor()Math.random()函数的原理。

翻译自: https://www.freecodecamp.org/news/generate-random-whole-numbers-within-a-range-javascript/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值