【问题标题】:(Javascript) How do I get a random number in between two user inputted variables? [duplicate](Javascript)如何在两个用户输入的变量之间获得一个随机数? [复制]
【发布时间】:2019-07-18 09:04:06
【问题描述】:

我正在处理一项任务,我很难编写函数来获取两个变量之间的随机数。

基本上我想要的是脚本提示您输入第一个数字,然后是第二个数字,然后在这两个数字之间给我一个随机数。

如何在两个用户输入的变量之间获得一个随机整数? 我做错了什么? 这是我的代码:

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));

这个问题与另一个问题不同,因为我的问题是两个变量之间的随机数。另一个答案对我不起作用。 再次感谢!

【问题讨论】:

  • 代码失败了吗?你有错误吗?预期结果与您得到的结果是什么?
  • certainperformance 回答了我的问题,谢谢,它没有正确加起来

标签: javascript variables random


【解决方案1】:

你需要先算出哪个变量更小,这样最后加的数越小,这样差(high - low)就是正数。您还需要确保您使用的是 numbers - 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));

【讨论】:

  • 问题在于,如果他们是 25 岁,并且一个月玩 30 个小时,或者是 30 岁,一个月玩 25 个小时,有没有办法在两者之间取一个随机数?两个变量?根据用户输入,一个变量将高于另一个变量。
  • 是的,这正是答案的作用——它确定下限和上限,然后将差值乘以 Math.random() 并加上下限。
  • 你这个摇滚人,我要试试,谢谢!!!
  • 我该怎么做?
  • 你介意再帮我一个问题吗?我在单独的帖子中发布了它,我觉得我很接近但我无法弄清楚
猜你喜欢
  • 2014-04-17
  • 1970-01-01
  • 2019-08-19
  • 2019-10-18
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 2012-04-25
  • 2021-06-15
相关资源
最近更新 更多