如何使循环重复另一个循环?

时间:2016-08-15 20:48:19

标签: java arrays loops for-loop

下面的代码为您提供了一个在运行程序时接近pi的数字。它需要用户输入您想要在每次试验中投掷的飞镖数量,并使用它来得出接近pi的数字。我需要为特定数量的试验运行代码,但似乎无法使其工作。我该怎么做?

    System.out.print("How many darts per trial? ");
    int darts = in.nextInt();
    System.out.print("How many trials? ");
    int trials = in.nextInt();   

    //The code below this represents 1 trial
    for(int i = 0; i < darts; i++)
    {
        xInt[i] = (Math.random() * (upper - lower)) + lower;
        yInt[i] = (Math.random() * (upper - lower)) + lower;
        c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2);
        c[i] = Math.sqrt(c2[i]);

        if(c[i] <= 1)
        {
            hits++;                 
        }                    
    }
    double answer = 4 * ((double)hits / (double)darts);            
    System.out.println(answer);

如果我为试验添加了for循环(见下文),那么它会将所有答案相加并打印总和

for(int n = 0; n < trials; n++)
    {
        for(int i = 0; i < darts; i++)
        {
            xInt[i] = (Math.random() * (upper - lower)) + lower;
            yInt[i] = (Math.random() * (upper - lower)) + lower;
            c2[i] = Math.pow(xInt[i], 2) + Math.pow(yInt[i], 2);
            c[i] = Math.sqrt(c2[i]);  
            if(c[i] <= 1)
                hits++;
        }
    }

    double answer = 4 * ((double)hits / (double)darts);            
    System.out.println(answer);

完成后应打印出类似的内容。

Trial [1]: pi = 3.11341744
Trial [2]: pi = 3.04824237
Trial [3]: pi = 3.33281081
Trial [4]: pi = 3.40901039

0 个答案:

没有答案