该计划的目的是找到pi的估计值。起初它运行但值太大(20,30,,40,etc)
现在它甚至没有编译。我收到ArrayIndexOutOfBoundsException
错误。
你会如何修复代码?感谢。
import java.util.Scanner;
import java.lang.Math;
import java.util.Random;
import java.io.File;
import java.io.IOException;
public class Darts
{
public static double[] getPi(double[] pi, int trials, int times, int counter)
{
for (int loop = 0; loop < trials; loop++)
{
for (int r = 0; r < times; r++)
{
double x = Math.random();
double y = Math.random();
if (Math.pow(x,2) + Math.pow(y,2) <= 1)
{
counter++;
}
}
pi[trials] = 4 * (double) counter / times;
}
return pi;
}
public static void printResults(double[] pi, int trials, double average)
{
for (int x = 0; x < trials; x++)
{
System.out.println("Trial [ " + x + "]: pi = " + pi[x]);
}
System.out.println("Estimate of pi = " + average );
}
public static void main (String [ ] args) throws IOException
{
Scanner in = new Scanner(System.in);
int counter = 0;
double y = 0;
double x = 0;
double radius = 1.0;
Random randNumList = new Random();
System.out.println("How many times darts should be thrown in a trial?");
int times = in.nextInt();
System.out.print("How many trials will there be?");
int trials = in.nextInt();
System.out.println(" " + trials + " trials");
double pi[] = new double[trials];
pi = getPi(pi, times, trials, counter);
double sumPi = 0.0;
for (int l = 0; l < trials; l++)
{
sumPi += pi[l];
}
double average = sumPi/counter;
printResults(pi, trials, average);
}
}
答案 0 :(得分:1)
你的话在这里:
pi[trials] = 4 * (double) counter / times;
应该是:
pi[loop] = 4 * (double) counter / times;