[英]Random number generator problems
我的問題是下面的代碼是否正確地生成了一個隨機數,如在最近20次嘗試中我得到500 000次5次,這根本沒有反映出獲得它的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;
}
我將您的代碼綁定到簡單的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);
}
}
當我多次運行它時,它生成的大多數是500000的2倍,與您2%的機率相匹配(98和99)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.