我正在尝试创建一个随机数生成器,它在两个数字之间生成随机数。例如,假设我想生成一个 4 到 10 之间的随机数,我希望它能够从 4 到 10 之间的任何数字中进行选择。这是我尝试过的:
var randNumMin = 4;
var randNumMax = 10;
var randInt = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
但是,这似乎不起作用,并生成了不在 4 到 10 之间的奇怪随机数,有些以 0 开头。正确的算法是什么?
这是我在其中实现算法的代码:
$(function() {
$('#generateRandNums').click(function() {
var numCount = document.getElementById("randNumCount").value;
var randNumMin = document.getElementById("randNumMin").value;
var randNumMax = document.getElementById("randNumMax").value;
if (numCount.match(/^[\d]*$/ ) && randNumMin.match(/^[\d]*$/ ) && randNumMax.match(/^[\d]*$/ )) {
if (numCount == "" || randNumMin == "" || randNumMax == "") {
alert ("Please fill out all forms then try again.");
} else {
if (randNumMin>randNumMax) {
alert ("Please make sure your first number is smaller than the second, then try again.");
} else {
if (randNumMin<0) {
alert ("Please make sure that you generate a positive number of random numbers, then try again.");
} else {
if (numCount>1) {
var randResult = ("You generated " + numCount + " random numbers between " + randNumMin + " and " + randNumMax + " and got the numbers ")
oneNumber = 0;
} else {
var randResult = ("You generated a random number between " + randNumMin + " and " + randNumMax + " and got the number ");
oneNumber = 1;
}
for (i=0;i<numCount;i++) {
//Get a random number between randNumMin and randNumMax
var randInt = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
if (i == numCount-1) {
if (oneNumber == 0) {
randResult = (randResult + "and " + randInt + ".");
} else {
randResult = (randResult + randInt + ".");
}
} else {
randResult = (randResult + randInt + ", ");
}
}
$("#randNumResults").val(randResult);
}
}
}
} else {
alert ("Make sure you only enter numbers and no spaces, then try again.");
}
});
});
我也尝试用这个替换 randInt 行:
var randInt = Math.floor((Math.random() * ((randNumMax + 1) - randNumMin)) + randNumMin);
它仍然没有工作。我不确定算法是否错误,或者我将其错误地合并到函数中。感谢您的回答,谢谢。