我正在尝试制作一个程序,使用随机数字计算骰子卷,并返回不同数量的卷和试验发生的每个总和的概率。然而,该代码仅导致零显示的概率。这似乎是在嵌套for循环中建立匹配变量的问题。想知道我做错了什么。是否根据计数器建立匹配变量?
import java.util.Random;
import java.util.Scanner;
public class DiceProbability
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random randNumList = new Random();
System.out.println("How many sides do the dice have: ");
int diceSides = in.nextInt();
System.out.println("How many times will the dice be rolled: ");
int diceRolls = in.nextInt();
int highestSum = diceSides * 2;
int diceRoll1 = 0;
int diceRoll2 = 0;
int match = 0;
int totalOfDiceRolls = 0;
int counter = 0;
int counter2 = 0;
System.out.println("Rolls total " + "Probability");
for(counter=2;counter<=highestSum;counter ++)
{
for(counter2=1;counter2<=diceRolls;counter2 ++)
{
diceRoll1 = (randNumList.nextInt(11)+1);
diceRoll2 = (randNumList.nextInt(11)+1);
int totalOfRolls = diceRoll1 + diceRoll2;
if(totalOfDiceRolls != counter)
{
match = match + 0;
}
else
{
match ++;
}
}
System.out.println(match);
double probabilityOfSum = (match * 100 / diceRolls);
System.out.println(counter + ": " + probabilityOfSum);
counter2 = 1;
}
}
}
答案 0 :(得分:1)
如果我理解正确的话,你试图计算两个骰子总和的相对频率。如果是这种情况,请编辑您的问题,因为您的询问并不明确,特别是您总是有两个骰子。
如果你有双面骰子,你的数学概率如下:
P(of having 2) = 1/4
P(of having 3) = 2/4
P(of having 4) = 1/4
所有其他人都等于0。
以下是实现此目的的代码。您需要将频率保存在数组中并正确输出除以实验数。
注意:如果你运行一个小于1000的数字,这在数学上是不准确的,所以在这种情况下用户输入实验的数量并不合理......(在我看来)
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("How many sides do one dice have: ");
int diceSides = in.nextInt();
int[] results = new int[diceSides * 2 + 1];
Random rnd = new Random();
for (int i = 0; i < 10000; i++) {
int resultdice1 = rnd.nextInt(diceSides) + 1;
int resultdice2 = rnd.nextInt(diceSides) + 1;
int sum = resultdice1 + resultdice2;
results[sum] = results[sum] + 1;
}
for (int i = 0; i < results.length; i++) {
System.out.println("Probability to have sum of " + i + " is : " + (double) results[i] / 10000);
}
}
输出: