首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >随机数发生器问题

随机数发生器问题
EN

Stack Overflow用户
提问于 2015-06-09 20:11:45
回答 1查看 84关注 0票数 0

我的问题是,下面的代码是否正确地生成了一个随机数,就像在过去的20次尝试中,我得到了500,000次,这并没有反映出得到它的2%的可能性。

代码语言:javascript
复制
  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;
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-09 20:25:07

我将您的代码绑定在简单的main方法中,并且工作正常。你自己试试看:

代码语言:javascript
复制
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)相匹配。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30741911

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档