Generating random whole numbers in JavaScript in a

2018-12-30 23:21发布

How can I generate a random whole number between two specified variables in Javascript, e.g. x = 4 and y = 8 would output any of 4, 5, 6, 7, 8?

26条回答
孤独寂梦人
2楼-- · 2018-12-31 00:12

this is my take on a random number in a range, as in I wanted to get a random number within a range of base to exponent. e.g. base = 10, exponent = 2, gives a random number from 0 to 100, ideally, and so on.

if it helps use it, here it is:

// get random number within provided base + exponent
// by Goran Biljetina --> 2012

function isEmpty(value){
    return (typeof value === "undefined" || value === null);
}
var numSeq = new Array();
function add(num,seq){
    var toAdd = new Object();
     toAdd.num = num;
     toAdd.seq = seq;
     numSeq[numSeq.length] = toAdd;
}
function fillNumSeq (num,seq){
    var n;
    for(i=0;i<=seq;i++){
        n = Math.pow(num,i);
        add(n,i);
    }
}
function getRandNum(base,exp){
    if (isEmpty(base)){
        console.log("Specify value for base parameter");
    }
    if (isEmpty(exp)){
        console.log("Specify value for exponent parameter");
    }
    fillNumSeq(base,exp);
    var emax;
    var eseq;
    var nseed;
    var nspan;
    emax = (numSeq.length);
    eseq = Math.floor(Math.random()*emax)+1;
    nseed = numSeq[eseq].num;
    nspan = Math.floor((Math.random())*(Math.random()*nseed))+1;
    return Math.floor(Math.random()*nspan)+1;
}

console.log(getRandNum(10,20),numSeq);
//testing:
//getRandNum(-10,20);
//console.log(getRandNum(-10,20),numSeq);
//console.log(numSeq);
查看更多
倾城一夜雪
3楼-- · 2018-12-31 00:13

To get a random number say between 1 and 6, first do:

    0.5 + (Math.random() * ((6 - 1) + 1))

This multiplies a random number by 6 and then adds 0.5 to it. Next round the number to a positive integer by doing:

    Math.round(0.5 + (Math.random() * ((6 - 1) + 1))

This round the number to the nearest whole number.

Or to make it more understandable do this:

    var value = 0.5 + (Math.random() * ((6 - 1) + 1))
    var roll = Math.round(value);
    return roll;

In general the code for doing this using variables is:

    var value = (Min - 0.5) + (Math.random() * ((Max - Min) + 1))
    var roll = Math.round(value);
    return roll;

The reason for taking away 0.5 from the minimum value is because using the minimum value alone would allow you to get an integer that was one more than your maximum value. By taking away 0.5 from the minimum value you are essentially preventing the maximum value from being rounded up.

Hope that helps.

查看更多
登录 后发表回答