Files
freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-within-a-range.md
2023-04-20 09:08:02 -05:00

2.1 KiB

id, title, challengeType, videoUrl, forumTopicId, dashedName
id title challengeType videoUrl forumTopicId dashedName
cf1111c1c12feddfaeb2bdef 生成某个范围内的随机整数 1 https://scrimba.com/c/cm83yu6 18187 generate-random-whole-numbers-within-a-range

--description--

You can generate a random whole number in the range from zero to a given number. You can also pick a different lower number for this range.

You'll call your minimum number min and your maximum number max.

This formula gives a random whole number in the range from min to max. 仔细看看并尝试理解这行代码到底在干嘛:

Math.floor(Math.random() * (max - min + 1)) + min

--instructions--

Create a function called randomRange that takes a range myMin and myMax and returns a random whole number that's greater than or equal to myMin and less than or equal to myMax.

--hints--

randomRange 返回的随机数应该大于或等于 myMin

assert(calcMin === 5);

randomRange 返回的随机数应该小于或等于 myMax

assert(calcMax === 15);

randomRange 应该返回一个随机整数,而不是小数。

assert(randomRange(0, 1) % 1 === 0);

randomRange 应该使用 myMaxmyMin,并且返回两者之间的随机数。

assert(
  (function () {
    if (
      code.match(/myMax/g).length > 1 &&
      code.match(/myMin/g).length > 2 &&
      code.match(/Math.floor/g) &&
      code.match(/Math.random/g)
    ) {
      return true;
    } else {
      return false;
    }
  })()
);

--seed--

--after-user-code--

var calcMin = 100;
var calcMax = -100;
for(var i = 0; i < 100; i++) {
  var result = randomRange(5,15);
  calcMin = Math.min(calcMin, result);
  calcMax = Math.max(calcMax, result);
}
(function(){
  if(typeof myRandom === 'number') {
    return "myRandom = " + myRandom;
  } else {
    return "myRandom undefined";
  }
})()

--seed-contents--

function randomRange(myMin, myMax) {
  return 0;
}

--solutions--

function randomRange(myMin, myMax) {
  return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}