当模拟掷骰子 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("nnnRoll 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,即两个骰子掷出的次数。有什么解决方法吗?
问题是您在每次滚动后都没有重置计数变量
消除count++
,只做arr[j]++
.
编辑
如评论中所述,循环是不必要的,因为您可以只做arr[sumOfRolls]++
。