简体   繁体   English

无法抵抗工作

[英]Can't get counter to work

I'm really new at this so forgive my ignorance.. So this is what I need to do: 我真的很陌生,所以请原谅我的无知。所以这是我需要做的:

  1. Determine how many bottle caps each person has to open in order to find a winning cap. 确定每个人必须打开多少个瓶盖才能找到获奖的瓶盖。 The answer is 1 in 5. 答案是五分之一。
  2. Prompt the user for the number of trials. 提示用户输入试用次数。
  3. Read back the data for all of the trials from the output file. 从输出文件中读取所有试验的数据。
  4. Calculate the average number of caps opened in order to win a prize. 计算为赢得奖品而打开的瓶盖的平均数量。
  5. Print the result to the screen. 将结果打印到屏幕上。

This is what I've tried, but the counter isn't working.. Help? 这是我尝试过的方法,但是计数器不起作用。

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();
    }
 }

A problem you may be facing is dividing two int and expecting a double result 您可能面临的问题是将两个int相除并期望得到double结果

int trials = 0;
int winCounter = 0;
double average;

average = winCounter / trials;

What's going to happen divding two int is that you will lose precision. int分为两个int将导致精度下降。 instead make the int into double . 而是使int成为double Or at least one of them. 至少其中之一。

double trials = 0;
double winCounter = 0;
double average;

average = winCounter / trials;

And use in.nextDouble() 并使用in.nextDouble()

Actually, your loop/counter is working. 实际上,您的循环/计数器正在运行。 What the problem is is that average calculation isn't correct. 问题是平均计算不正确。 You need to make sure the division numbers are treated as floats. 您需要确保将分区号视为浮点数。 So either do the below calculation, making sure winCounter and trials are both treated as floats: 因此,请执行以下计算,确保将winCounter和trial都视为浮点数:

average = (float) winCounter / (float) trials;

Or declare winCounter and trials as floats. 或者将winCounter和trial声明为float。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM