gpt4 book ai didi

java - 随机数生成器问题

转载 作者:行者123 更新时间:2023-12-02 04:35:57 25 4
gpt4 key购买 nike

我的问题是下面的代码是否正确生成了一个随机数,因为在过去 20 次尝试中我得到了 500 000 5 次,这并不反射(reflect)得到它的 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;
}

最佳答案

我将您的代码绑定(bind)到简单的 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)相匹配

关于java - 随机数生成器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30741911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com