簡體   English   中英

無法抵抗工作

[英]Can't get counter to work

我真的很陌生,所以請原諒我的無知。所以這是我需要做的:

  1. 確定每個人必須打開多少個瓶蓋才能找到獲獎的瓶蓋。 答案是五分之一。
  2. 提示用戶輸入試用次數。
  3. 從輸出文件中讀取所有試驗的數據。
  4. 計算為贏得獎品而打開的瓶蓋的平均數量。
  5. 將結果打印到屏幕上。

這是我嘗試過的方法,但是計數器不起作用。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM