admin管理员组文章数量:1194547
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. :)
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. :)
Share Improve this question asked Mar 3, 2011 at 21:49 JoshJosh 1,4215 gold badges23 silver badges33 bronze badges 1- 10 What happens if you pick a random integer number and multiply that by 10? – 6502 Commented Mar 3, 2011 at 21:51
7 Answers
Reset to default 12I 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.
本文标签: javascriptMaking a random number that39s a multiple of 10Stack Overflow
版权声明:本文标题:javascript - Making a random number that's a multiple of 10 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738502579a2090351.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论