我真的很新,所以请原谅我的无知.. 所以这就是我需要做的:
- 确定每个人必须打开多少个瓶盖才能找到获胜的瓶盖。答案是五分之一。
- 提示用户输入试验次数。
- 从输出文件中读回所有试验的数据。
- 计算为赢得奖品而打开的平均上限数。
- 将结果打印到屏幕上。
这是我试过的方法,但计数器不工作..帮助?
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();
}
}
最佳答案
您可能面临的一个问题是将两个 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()
关于java - 无法抗拒工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20947152/