首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript (html) Math.random()范围不工作

Javascript (html) Math.random()范围不工作
EN

Stack Overflow用户
提问于 2020-10-20 03:55:04
回答 2查看 276关注 0票数 0

我想在“最低值”和“最高值”之间生成一个随机数。它们是用户的输入。

我在我的代码中使用了这段代码,但是生成的数字不在范围之内。

代码语言:javascript
复制
var secret = Math.floor(Math.random()*(highestnum-lowestnum+1)+lowestnum); 

例如:我输入了lowest=4,highest=6,应该是4/5/6,但是实际上,生成的数字是0/1/ 2,我发现这是因为6-4是2,它只会生成0到2,这是数字之间的区别,而不是4到6之间的任何数字。

编辑!更新的更清晰的问题

这些是它的html内部的内容。

代码语言:javascript
复制
<input id="highestnum" type="text" name="highestnum"> ```

and inside javascript is this 
```var lowestnum = document.getElementById("lowestnum").value; 

document.getElementById(" highestnum ").value;

变量机密= Math.floor(Math.random()*(highestnum-lowestnum+1)+lowestnum);`

代码语言:javascript
复制
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-10-20 04:04:18

尝尝这个。

代码语言:javascript
复制
function randomNumber() 
{

    var lowestnum =  parseInt(document.getElementById("lowestnum").value);
    var highestnum = parseInt(document.getElementById("highestnum").value);
    secret=Math.floor(Math.random() * (Math.abs(highestnum - lowestnum) + 1) + lowestnum); 
    console.log(secret);
}

window.onload = function() {

document.addEventListener('keyup', function(event) {
    var lowestnum =  document.getElementById("lowestnum");
    var highestnum = document.getElementById("highestnum");
if (event.target === lowestnum || event.target === highestnum ) {
    if(lowestnum.value.length > 0 && highestnum .value.length>0){
        document.getElementById("button").removeAttribute("disabled");
    }
    else{
        document.getElementById("button").setAttribute("disabled","true");
    }
}

}, false);

}
代码语言:javascript
复制
<input type="number" id="lowestnum">
<input type="number" id="highestnum">
<button type="button" disabled id="button">generate</button>

UPDATE只是将其解析为int

票数 2
EN

Stack Overflow用户

发布于 2020-10-20 04:22:52

根据MDN

获得0(包含)到1(独占)之间的随机数:

代码语言:javascript
复制
function getRandom() {
  return Math.random();
}

在两个值之间获得一个随机数:

代码语言:javascript
复制
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

在两个值之间获取一个随机整数:

代码语言:javascript
复制
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}

在两个值之间获取一个随机整数,包括:

代码语言:javascript
复制
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive 
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64438242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档