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 g开发者_StackOverflowet a number that's a multiple of 10 between two ranges.
Thanks. :)
I guess it can help:
var randomnumber=Math.floor(Math.random()*11)*10
it's just one line:
function rand_10(min, max){
return Math.round((Math.random()*(max-min)+min)/10)*10;
}
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));
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 randomfactorial
The factorial/incremental number- multiplies the random number generated to the maxNum.
- Rounds down the result.
- Divides by the factorial.
- Rounds down the result.
- then multiplies again by the factorial.
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.
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.
- Take the difference of the two parameters.
- Divide the difference by 10.
- Generate a random number from 0 to the result of the division.
- Multiply that by 10.
精彩评论