这个问题在这里已有答案:
我正在进行一项任务,我很难编写函数来获取两个变量之间的随机数。
基本上我想要的是脚本提示您输入第一个数字,然后是第二个数字,然后在这两个数字之间给我一个随机数。
如何在两个用户输入的变量之间获得随机整数?我做错了什么?这是我的代码:
var age = prompt("How old are you?");
var videogames = prompt("How many hours of video games have you played last month?");
function getRndInteger(age, videogames) {
return Math.floor(Math.random() * (videogames - age)) + age;
}
document.write(getRndInteger(age, videogames));
这个问题与另一个问题不同,因为我的是两个变量之间的随机数。另一个答案对我不起作用。再次感谢!
您需要首先确定哪个变量较小,以便最后添加的数字较低,因此差值(high - low)
为正数。您还需要确保使用数字 - prompt
返回一个字符串,因此+ <string>
将导致连接,而不是添加。
var age = prompt("How old are you?");
var videogames = prompt("How many hours of video games have you played last month?");
function getRndInteger(...args) {
const [low, high] = [Math.min(...args), Math.max(...args)];
return Math.floor(Math.random() * (high - low)) + low;
}
document.write(getRndInteger(age, videogames));
请注意,这会生成一个范围[low - high)
- 包含“低”点,“高”不包含。 (例如,从2-4的范围,2是可能的结果,3是,但4不是。)如果你想包括high
,添加一个差异:
var age = prompt("How old are you?");
var videogames = prompt("How many hours of video games have you played last month?");
function getRndInteger(...args) {
const [low, high] = [Math.min(...args), Math.max(...args)];
return Math.floor(Math.random() * (high - low + 1)) + low;
}
document.write(getRndInteger(age, videogames));