我真的很陌生,所以原谅我的无知...... 所以这就是我需要做的事情:
这是我试过的,但是计数器不起作用..帮助?
import java.util.Scanner;
import java.util.Random;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class BottleCapPrize
{
public static void main(String [] args) throws IOException
{
int trials = 0;
int loop = 1;
int winCounter = 0;
int random;
double average;
//
Scanner in = new Scanner(System.in);
Random rand = new Random();
PrintWriter outFile = new PrintWriter (new File("MonteCarloMethod.txt"));
//
System.out.print("Number of trials: ");
trials = in.nextInt();
//
for(loop = 1; loop <= trials; loop++)
{
random = rand.nextInt(5);
if(random == 1)
{
outFile.println("Trial: " + loop + " WIN!");
winCounter++;
}
outFile.println("Trial: " + loop + " LOSE");
}
//
average = winCounter / trials;
outFile.println("Average number of caps to win: " + average);
System.out.println("Average number of caps to win: " + average);
outFile.close();
}
}
答案 0 :(得分:1)
您可能遇到的问题是划分两个int
并期待double
结果
int trials = 0;
int winCounter = 0;
double average;
average = winCounter / trials;
将两个int
分开是会失去精确度的。而是将int
变为double
。或者至少其中一个。
double trials = 0;
double winCounter = 0;
double average;
average = winCounter / trials;
并使用in.nextDouble()
答案 1 :(得分:0)
实际上,你的循环/计数器正在运行。问题是平均计算不正确。您需要确保将分区编号视为浮点数。因此要么进行以下计算,要确保winCounter和试验都被视为浮点数:
average = (float) winCounter / (float) trials;
或者宣布winCounter和试验为浮动。