2.5 KiB
2.5 KiB
id, challengeType, videoUrl, forumTopicId, localeTitle
id | challengeType | videoUrl | forumTopicId | localeTitle |
---|---|---|---|---|
cf1111c1c12feddfaeb2bdef | 1 | https://scrimba.com/c/cm83yu6 | 18187 | 生成某个范围内的随机整数 |
Description
Math.floor(Math.random() * (max - min + 1)) + min
Instructions
randomRange
的函数,参数为 myMin 和 myMax,返回一个在myMin
(包括 myMin)和myMax
(包括 myMax)之间的随机数。
Tests
tests:
- text: <code>randomRange</code>返回的随机数应该大于或等于<code>myMin</code>。
testString: assert(calcMin === 5);
- text: <code>randomRange</code>返回的随机数应该小于或等于<code>myMax</code>。
testString: assert(calcMax === 15);
- text: <code>randomRange</code>应该返回一个随机整数, 而不是小数。
testString: assert(randomRange(0,1) % 1 === 0 );
- text: <code>randomRange</code>应该使用<code>myMax</code>和<code>myMin</code>, 并且返回两者之间的随机数。
testString: 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;}})());
Challenge Seed
// Example
function ourRandomRange(ourMin, ourMax) {
return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}
ourRandomRange(1, 9);
// Only change code below this line.
function randomRange(myMin, myMax) {
return 0; // Change this line
}
// Change these values to test your function
var myRandom = randomRange(5, 15);
After Test
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";
}
})()
Solution
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}