该程序用于通过随机数的 throws(x,y 坐标)计算 Pi,然后迭代整个过程多次。
我在代码的最后一行出现错误 double average = average(pi),它说找不到符号变量 pi,即使我使用它并在 average 方法中声明它。
/*
@author
@version January 8th 2016
*/
import java.util.Scanner;
import java.util.Random;
import java.util.Random;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.IOException;
public class Darts2 {
public static int numThrows;
public static int numTrials;
public static int misses;
public static int hits;
public static void prompt() {
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
numTrials = in.nextInt();
}
public static double[] randomX( int numThrows){
int darts = 0;
int i = 0;
double[] cordX = new double[numThrows];
while(darts < numThrows - 1) {
cordX[i] = Math.random();
i++;
darts++;
}
return cordX;
}
public static double[]randomY(int numThrows) {
int darts = 0;
int i = 0;
double [] cordY = new double[numThrows];
while(darts < numThrows) {
cordY[i] = Math.random();
i++;
darts++;
}
return cordY;
}
public static void getHits(int numThrows, double[] cordX, double[] cordY) {
int ii = 0;
int i = 0;
hits = 0;
misses = 0;
for(i = 0; i < numThrows; i++) {
if( Math.pow(cordX[ii],2) + Math.pow(cordY[ii],2) <= 1) {
hits++;
} else{
misses++;
}
ii++;
}
}
public static double calcPi(int misses, int hits) {
int total = hits + misses;
double pi = 4 * ((double)hits / total);
return pi;
}
public static void print(double pi, int numThrows) {
System.out.printf("\nThe pi estimate for this trial is: " + pi);
}
public double average(double[] pi) {
double sum = 0;
double average;
for(int i = 0; i < pi.length; i++) {
sum = sum + pi[i];
}
average = (double)sum/pi.length;
return average;
}
public static void main(String[] args)throws IOException {
prompt();
int x = 0;
for(x = 0; x < numTrials; x++) {
double[] cordX = randomX(numThrows);
double[] cordY = randomY(numThrows);
getHits(numThrows, cordX, cordY);
double pi = calcPi(misses, hits);
print(pi, numThrows);
}
double average = average(pi);
}
}