【问题标题】:Rolling 2 six sided dice 1000 times, unexpected results掷 2 个六面骰子 1000 次,结果出人意料
【发布时间】:2020-04-29 16:24:48
【问题描述】:

在模拟掷 2 个骰子 1000 次并显示结果时,它不断返回意外值。我的程序是:

import java.util.*;

public class Prob1 {
    private int sides; //Amount of sides on die
    private int sumOfRolls; 
    private int[] arr; //Array that holds the count of each sum of the rolls
    private int count; //Temporarily holds value of sum of rolls before passing to array
    public Prob1() { //Default constructor, sets sides to 6
        sides = 6;
        sumOfRolls = 0;
        count =0;
        arr = new int[(sides*2)+1];
    }
    public void roll() { //Method that rolls the 2 dice
        for(int i=0;i<1000;i++) { //Repeats 1000 times
            int roll1 = (int) (Math.random()*sides)+1; //Rolls 1 die
            int roll2 = (int) (Math.random()*sides)+1; //Rolls other die
            sumOfRolls = roll1+roll2; //Sums both rolls
            for(int j=2;j<(sides*2)+1;j++) { //Goes through all the possible values of sums of roll
                if(sumOfRolls==j) { //Checks if sum of rolls is equal to the value presented by the for loop
                    count++; //Adds 1 to count of value of sum of roll
                    arr[j]=count; //Adds that value to array
                }
            }
        }
        System.out.println("Roll: " + sides + "-sided dice"); //Displays what kind of dice
    }
    public void frequency() { //Frequency table
        System.out.println("\n\n\nRoll Total  Frequency");
        System.out.println("---------------------");
        for(int i=2; i<(sides*2)+1; i++) { //Displays each value of array
            System.out.print(i + "           " + arr[i] + "\n");

        }

    }


}

同时调用滚动和频率方法时,结果如下:

Roll: 6-sided dice



Roll Total  Frequency
---------------------
2           952
3           995
4           976
5           989
6           991
7           999
8           1000
9           998
10           992
11           994
12           997

这是错误的,因为每个值的总和超过 1000,即两个骰子掷出的次数。有什么解决办法吗?

【问题讨论】:

  • 您不会在每次滚动后重置计数

标签: java arrays random dice


【解决方案1】:

问题是您没有在每次滚动后重置计数变量

去掉count++,只做arr[j]++

编辑

正如comments 中提到的,循环是不必要的,因为您可以只执行arr[sumOfRolls]++

【讨论】:

  • 如果没有循环,arr[sumOfRolls]++ 会不会更好?
  • @Andreas,确实
猜你喜欢
  • 2018-12-17
  • 2020-06-06
  • 2016-02-07
  • 2015-12-09
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 2021-04-06
相关资源
最近更新 更多