我的问题是,下面的代码是否正确地生成了一个随机数,就像在过去的20次尝试中,我得到了500,000次,这并没有反映出得到它的2%的可能性。
public static int randInt(int min, int max) {
// NOTE: Usually this should be a field rather than a method
// variable so that it is not re-seeded every call.
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public void prizegenerator(View v) {
int fate = randInt(0,100);
int reward=0;
if (fate <= 30) {
reward = 1000;
}
else if (fate <= 50) {
reward = 2000;
}
else if (fate <= 80) {
reward = 5000;
}
else if (fate <=90) {
reward = 10000;
}
else if (fate <= 95) {
reward = 50000;
}
else if (fate <= 97) {
reward = 100000;
}
else if (fate <= 99) {
reward = 500000;
}
else if (fate <= 100) {
reward = 1000000;
}发布于 2015-06-09 20:25:07
我将您的代码绑定在简单的main方法中,并且工作正常。你自己试试看:
public static void main(String[] args) {
Main main = new Main();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
list.add(main.prizegenerator());
}
Collections.sort(list);
for (Integer integer : list) {
System.out.println(integer);
}
}当我多次运行它时,它主要生成2乘500000,这与2%的几率( 98和99)相匹配。
https://stackoverflow.com/questions/30741911
复制相似问题