这个问题在这里已经有答案了:
整数除法:为什么1/3的结果==0((16个答案)
三年前关门了。
下面是我的代码,所有的东西都在工作,除了我每次生成的头和尾的平均数,每次都是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);
} }`
1条答案
按热度按时间wmvff8tz1#
您正在执行整数除法,它只返回结果的整数部分(不含小数部分),在您的情况下始终为0,因为正/尾数永远不会大于翻转数。要同时打印分数部分,您需要将结果转换为浮点值,如下所示: