我想在“最低值”和“最高值”之间生成一个随机数。它们是用户的输入。
我在我的代码中使用了这段代码,但是生成的数字不在范围之内。
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内部的内容。
<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);`
发布于 2020-10-20 04:04:18
尝尝这个。
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);
}<input type="number" id="lowestnum">
<input type="number" id="highestnum">
<button type="button" disabled id="button">generate</button>
UPDATE只是将其解析为int
发布于 2020-10-20 04:22:52
根据MDN
获得0(包含)到1(独占)之间的随机数:
function getRandom() {
return Math.random();
}在两个值之间获得一个随机数:
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}在两个值之间获取一个随机整数:
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
}在两个值之间获取一个随机整数,包括:
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
}https://stackoverflow.com/questions/64438242
复制相似问题