我的代码在下面,一切正常,除非我每次试用产生平均头尾数,每次都是0。它的代码位于底部,但我发布了我所做的一切,因为我不确定错误在哪里。我该如何解决这个问题?谢谢!!!!
import java.util.Random;
import java.util.Scanner;
public class CoinToss{
public static void main(String [] args)
{
int heads = 0;
int tails = 0;
int counter = 1;
double randNum = 0.0;
Scanner in = new Scanner(System.in);
//introduction
System.out.println("Welcome to the coin flip simulator!");
System.out.println("This program will simulate the average ");
System.out.println("number of heads and tails for 10, 100 ");
System.out.print("and 10000 flips of a coin. ");
//user input
System.out.println("How many times would you like to flip the coin? ");
System.out.print("choose 10,100, 1 ");
System.out.print("or 10000 ");
//scanner
int flips = in.nextInt();
while(counter <= flips)
{
randNum = Math.random();
System.out.print(counter + "\t" + randNum);
if(randNum < .5)
{
heads++;
System.out.println("\t heads");
}
else
{
tails++;
System.out.println("\t tails");
}
counter++;
}
System.out.println();
System.out.println("Number of Heads = " + heads);
System.out.println("Number of Tails = " + tails);
//average heads
System.out.println("Average number of times for 'heads':");
System.out.println(heads++/flips);
//average tails
System.out.println("Average number of times for 'tails':");
System.out.println(tails++/flips);
} }`
答案 0 :(得分:0)
您正在执行整数除法,它只返回结果的整数部分(没有小数部分),在您的情况下始终为0,因为磁头/尾部的数量永远不会大于翻转。要打印小数部分,您需要将结果转换为浮点数:
System.out.println((float) heads++/flips);