22

我正在尝试创建一个随机数生成器,它在两个数字之间生成随机数。例如,假设我想生成一个 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);

它仍然没有工作。我不确定算法是否错误,或者我将其错误地合并到函数中。感谢您的回答,谢谢。

4

5 回答 5

57

在特定范围内的 JavaScript 中生成随机整数?

/**
 * Returns a random number between min and max
 */
function getRandomArbitary (min, max) {
    return Math.random() * (max - min) + min;
}

/**
 * Returns a random integer between min and max
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

http://roshanbh.com.np/2008/09/get-random-number-range-two-numbers-javascript.html

//function to get random number upto m
function randomXToY(minVal,maxVal,floatVal)
{
    var randVal = minVal+(Math.random()*(maxVal-minVal));
    return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

或者

在 JavaScript 中生成两个数字之间的随机数

于 2012-04-13T01:46:06.213 回答
2

您的问题是您从未将字符串转换为数字尝试添加此

if (  numCount.match(/^[\d]*$/ ) && 
    randNumMin.match(/^[\d]*$/ ) && 
    randNumMax.match(/^[\d]*$/ )){
  if (numCount === "" || randNumMin === "" || randNumMax === "")  {
    alert ("Please fill out all forms then try again.");
  } else {
    numCount=numCount-0;randNumMin=randNumMin-0;randNumMax=randNumMax-0;

另一个注意事项,您需要将检查值是否为空字符串更改为严格相等。要了解我的意思,请尝试对其中一个值使用零。0 == ""//returns true因为两者都是虚假的0 === ""//returns false

于 2012-04-13T02:59:40.500 回答
2

Underscore.js对此 _.random(min,max) 有一个很好的实用程序

于 2014-04-07T20:46:48.693 回答
1

这个怎么样?

var max = 10;
var min = 4;
var random = Math.floor((Math.random() * ((max + 1) - min)) + min);
于 2012-04-13T01:52:26.220 回答
0

randojs.com使它成为一个简单的单行:

rando(4, 10)

您只需将其添加到您的 html 文档的头部,您就可以轻松地随心所欲地做任何您想做的事情。来自数组的随机值、随机 jquery 元素、来自对象的随机属性,甚至在需要时防止重复。

<script src="https://randojs.com/1.0.0.js"></script>
于 2019-12-02T02:44:39.913 回答