Random number with fixed length

2019-04-10 16:18发布

I want to generate a random integer number with 0-9 numbers and with length = 5. I try this:

function genRand(min,max) {
    for (var i = 1; i <= 5; i++) {
        var range = max - min + 1;
        return Math.floor(Math.random()*range) + min;
    }
}

and call:

genRand(0,9);

But it always returns 1 number, not 5 (

Help please!

5条回答
\"骚年 ilove
2楼-- · 2019-04-10 16:31

The smallest 5 digit number is 10000, the largest is 99999, or 10000+89999.

Return a random number between 0 and 89999, and add it to the minimum.

var ran5=10000+Math.round(Math.floor()*90000)

Math.floor rounds down, and Math.random is greater than or equal to 0 and less than 1.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-04-10 16:33
   function genRand() {
      return Math.floor(Math.random()*89999+10000);
   }
查看更多
smile是对你的礼貌
4楼-- · 2019-04-10 16:36

Here's a more generalized version of Nate B's answer:

function rand(digits) {
    return Math.floor(Math.random()*parseInt('8' + '9'.repeat(digits-1))+parseInt('1' + '0'.repeat(digits-1)));
}
查看更多
\"骚年 ilove
5楼-- · 2019-04-10 16:51

To get a 5 digit random number generate random numbers between the range (10000, 99999). Or generate randomly 5 single digits and paste them.

EDIT

The process you have shown simply will generate one number and return to the caller. The think which might work is (pseudo code) :

int sum = 0;
int m = 1;
for (i=0;i<5;i++)
{
  sum = sum  + m * random (0, 9);
  /*       or                  */
  sum = sum * m + random (0, 9);
  m = m * 10;
}

Or better generate 5 digit random numbers with rand (10000, 99999)

查看更多
我只想做你的唯一
6楼-- · 2019-04-10 16:52

return exits the function on the first loop.

查看更多
登录 后发表回答