Making a random number that's a multiple of 10

2019-02-19 02:19发布

问题:

I'm looking to create a random number between two ranges that is a multiple of 10.

For example, if I fed the function the parameters 0, 100 it would return one of these numbers:

0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100

but nothing like 63 or 55.

And yes I'm aware this defeats the point of true "randomness", but I just need a quick easy way to get a number that's a multiple of 10 between two ranges.

Thanks. :)

回答1:

I guess it can help:

var randomnumber=Math.floor(Math.random()*11)*10


回答2:

it's just one line:

function rand_10(min, max){
    return Math.round((Math.random()*(max-min)+min)/10)*10;
}


回答3:

Use a normal random number function like this one:

function GetRandom( min, max ) {
    if( min > max ) {
        return( -1 );
    }
    if( min == max ) {
        return( min );
    }

    return( min + parseInt( Math.random() * ( max-min+1 ) ) );
}

As this will only return integers ("multiples of 1"), you can multiply by 10 and get only multiples of 10.

randomNumberMultipleOfTen = GetRandom(0,10) * 10;

Of course you can merge both into one function if you want to, I'll leave this as an exercise to you.



回答4:

  1. Take the difference of the two parameters.
  2. Divide the difference by 10.
  3. Generate a random number from 0 to the result of the division.
  4. Multiply that by 10.

HTH.



回答5:

This seems to do the work

Math.floor(Math.random() * 10) * 10

If you modify that a little you can easily make it between any two numbers.



回答6:

var a = 67;
var b = 124;
var lo = a + 10 - (a % 10) 
var hi = b - (b % 10)
var r = lo + 10 * parseInt(Math.random() * ((hi - lo)/10 + 1));


回答7:

function rand(maxNum, factorial) { 
    return Math.floor(Math.floor(Math.random() * (maxNum + factorial)) / factorial) * factorial; 
};

Takes two parameter

  • maxNum Maximum number to be generated in random
  • factorial The factorial/incremental number

    1. multiplies the random number generated to the maxNum.
    2. Rounds down the result.
    3. Divides by the factorial.
    4. Rounds down the result.
    5. then multiplies again by the factorial.