生成随机整数从最小至最大? [英] Generate Random Integer from Min to Max?
本文介绍了生成随机整数从最小至最大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要生成一个随机整数是:
- 在区间[最小,最大]
包括
- 的范围可以是[5,20],[-29,-3]或[-13,13](它可以在任何范围内,正或负或之间)的
- 的code采用的是Android做工精细
我走到这一步,是这样的,但似乎不负范围的工作!
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:
- Inside the range [Min, Max]
inclusive
- The range can be [5,20], [-29, -3] or [-13, 13] (It can be in any range, positive or negative or in between)
- The code is working fine in Android
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.
这篇关于生成随机整数从最小至最大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文