我要生成一个随机整数是:
我走到这一步,是这样的,但似乎不负范围的工作!
1 +(INT)(的Math.random()*((最大值 - 最小值)+ 1));解决方案
我是pretty确定要将
敏+(INT)(的Math.random()*((最大值 - 最小值)+ 1));不过,我要指出的范围[-3,-29]有它的最小和最大逆转。 (而且具有相同的[5,1 -13]作为通过Merlyn指出)。
如果你想只是把任意两个号码的范围,a和b然后使用code
诠释最小= Math.min(A,B);INT最大= Math.max(A,B);这样,你将不必担心秩序。这甚至会为一个== b工作。
I want to generate a random Integer that is:
What I got so far is this, but it seems not working with negative ranges !
1 + (int)(Math.random() * ((Max - Min) + 1));解决方案
I'm pretty sure you want
Min+(int)(Math.random()*((Max-Min) + 1));However, I should point out that the range [-3,-29] has its min and max reversed. (And the same with [5,-13] as was pointed out by Merlyn.)
If you want to just put in any two numbers for the range, a and b then use the code
int Min = Math.min(a,b); int Max = Math.max(a,b);That way you won't have to worry about the order. This will even work for a==b.