gpt4 book ai didi

java - 计算使用java中的Random()方法生成的数字的平均值

转载 作者:太空宇宙 更新时间:2023-11-04 10:59:36 25 4
gpt4 key购买 nike

我的代码如下,一切正常,除了当我生成每次试验的平均正面和反面数量时,它每次都显示为 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,因为正面/反面的数量永远不会大于翻转的数量。要打印小数部分,您需要将结果转换为 float ,如下所示:

System.out.println((float) heads++/flips);

关于java - 计算使用java中的Random()方法生成的数字的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47038781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com