3.4 KiB
3.4 KiB
id, title, challengeType, videoUrl, forumTopicId, localeTitle
id | title | challengeType | videoUrl | forumTopicId | localeTitle |
---|---|---|---|---|---|
cf1111c1c12feddfaeb1bdef | Generate Random Whole Numbers with JavaScript | 1 | https://scrimba.com/c/cRn6bfr | 18186 | Генерировать случайные целые числа с помощью JavaScript |
Description
- Используйте
Math.random()
для генерации случайного десятичного знака. - Умножьте это случайное число на
20
. - Используйте другую функцию,
Math.floor()
чтобы округлить число до его ближайшего целого числа.
Math.random()
никогда не может полностью вернуть 1
и, поскольку мы округливаем, на самом деле получить 20
невозможно. Этот метод даст нам целое число от 0
до 19
. Соединяя все вместе, это выглядит как наш код: Math.floor(Math.random() * 20);
Мы вызываем Math.random()
, умножая результат на 20, затем передавая значение функции Math.floor()
чтобы округлить значение до ближайшего целого числа.
Instructions
0
до 9
.
Tests
tests:
- text: The result of <code>randomWholeNum</code> should be a whole number.
testString: assert(typeof randomWholeNum() === "number" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})());
- text: You should be using <code>Math.random</code> to generate a random number.
testString: assert(code.match(/Math.random/g).length > 1);
- text: You should have multiplied the result of <code>Math.random</code> by 10 to make it a number that is between zero and nine.
testString: assert(code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) || code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g));
- text: You should use <code>Math.floor</code> to remove the decimal part of the number.
testString: assert(code.match(/Math.floor/g).length > 1);
Challenge Seed
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
// Only change code below this line.
return Math.random();
}
After Tests
(function(){return randomWholeNum();})();
Solution
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
return Math.floor(Math.random() * 10);
}