int randomWithRange(int min, int max)
{
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
Output of randomWithRange(2, 5)
10 times:
(randomWithRange(2, 5)
输出10次:)
5
2
3
3
2
4
4
4
5
4
The bounds are inclusive, ie [2,5], and min
must be less than max
in the above example.
(边界是包容性的,即[2,5],并且在上面的例子中min
必须小于max
。)
EDIT: If someone was going to try and be stupid and reverse min
and max
, you could change the code to:
(编辑:如果有人要尝试愚蠢并反转min
和max
,您可以将代码更改为:)
int randomWithRange(int min, int max)
{
int range = Math.abs(max - min) + 1;
return (int)(Math.random() * range) + (min <= max ? min : max);
}
EDIT2: For your question about double
s, it's just:
(编辑2:关于double
s的问题,它只是:)
double randomWithRange(double min, double max)
{
double range = (max - min);
return (Math.random() * range) + min;
}
And again if you want to idiot-proof it it's just:
(再次,如果你想要愚蠢的证明它只是:)
double randomWithRange(double min, double max)
{
double range = Math.abs(max - min);
return (Math.random() * range) + (min <= max ? min : max);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…