我学习Java的动态变化数 - 碰到这样的问题:嵌套的for循环
编写滚动骰子ň,其中骰子都是d片面的程序。通过 使用模拟,使用骰子报告概率为 的总概率x或更大的概率值,其中x,n和d全部作为输入给出 。例如,如果n = 2,d = 6和x = 7,则程序 应报告58.3%的概率(大约)。
这是我想出了
public class Main {
public double calcProbability(int n, int d, int x){
int[] sums = new int[(int)Math.pow(d, n)]; //Creates an array of max size needed
int counter = 0;
int occurrences = 0; //No. of times that the number being added to the array is greater than d
for(int i=1;i<=d;i++){
for(int j=1;j<=d;j++){
if((i+j)>=x){
occurrences++;
}
sums[counter]=(i+j);
counter++;
}
}
return (double)occurrences/Math.pow(d, n); //Returning probability
}
public static void main(String[] args) {
System.out.println(new Main().calcProbability(2, 6, 7));
}
}
它工作正常的N = 2(我认为),因为我使用两个嵌套的for循环。但是我无法弄清楚如何用n来改变for循环的数量(这将允许我将所有可能的总和添加到数组中 - 其余代码应该按原样工作)。
希望能得到一些指导。
谢谢大家,考虑到每个人的贡献后,这里的修订方法:
public double calcProbability(int n, int d, int x){
Random random = new Random(); //Random numbers simulate dice rolling
int occurrences = 0; //No. of times that the number is greater than d
for(int i=0;i<100000;i++)
{
int sum = 0;
for(int j=0;j<n;j++)
{
sum+=random.nextInt(d)+1;
}
if(sum>=x) {
occurrences++;
}
}
return (double)occurrences/100000; //Will be an approximation
}
这是毫无意义的保存这些数字,然后计算发生的次数 - 而仅计算发生时,它需要放置并继续前进。
您可以在没有模拟的情况下计算确切的更改。 –
添加到@PeterLawrey:你**不能**用模拟计算概率。你必须拿出一个公式,并解决给定输入的公式 – luk2302
即使对于给定的输入,我也不确定这是否会回答问题。你不是“滚动骰子”,因为我知道你应该使用随机数字发生器。这个想法不是要计算概率值(可以用手来完成),而是模拟掷骰子并验证它是否收敛到某个值。 –