开发者

Problems While Trying To Generate Random Numbers

I'm trying to 开发者_运维百科build a web application that generates a random number within a range(from/to) using this code:

function generateRandom(rFrom, rTo)
{
    var num;
    num = Math.floor(rFrom + (1 + rTo - rFrom) * Math.random());

    return num;
}

function btGenerate_onClick(event)
{
    var nFrom;
    var nTo;

    nFrom = document.getElementById("txtFrom").value;
    nTo = document.getElementById("txtTo").value;

    document.getElementById("lblResult").innerText = generateRandom(nFrom, nTo);
}

But while I was testing the web application using the properties 2 and 5 for From and To respectively, I got numbers like 22, 210, 20, 27 and 211. So how I can correct this so it will generate numbers that are between 2 and 5 as tried without sucess?


The problem is that you have to explicitly turn the string values into numbers:

function generateRandom(rFrom, rTo)
{
    var num;
    rFrom = Number(rFrom); rTo = Number(rTo);
    num = Math.floor(rFrom + (1 + rTo - rFrom) * Math.random());

    return num;
}

The multiplication will do it implicitly for "rTo", but then you have to make "rFrom" a number for the addition, or else it'll be interpreted as string concatenation.

edit — oops I started with the wrong block of code. This now has your original function, and all I changed was to explicitly convert the parameters to numbers.


function generateRandom(rFrom, rTo)
{
    var num;
    num = Math.floor(Math.random()*parseInt(rTo)) + parseInt(rFrom);

    return num;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜