[英]Can't get counter to work
I'm really new at this so forgive my ignorance.. So this is what I need to do: 我真的很陌生,所以请原谅我的无知。所以这是我需要做的:
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.