[英]Can't get counter to work
我真的很陌生,所以請原諒我的無知。所以這是我需要做的:
這是我嘗試過的方法,但是計數器不起作用。
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
將導致精度下降。 而是使int
成為double
。 或至少其中之一。
double trials = 0;
double winCounter = 0;
double average;
average = winCounter / trials;
並使用in.nextDouble()
實際上,您的循環/計數器正在運行。 問題是平均計算不正確。 您需要確保將分區號視為浮點數。 因此,請執行以下計算,確保將winCounter和trial都視為浮點數:
average = (float) winCounter / (float) trials;
或者將winCounter和trial聲明為float。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.