mardi 31 octobre 2017

Calculating average for numbers generated using Random() method in java

My code is below, everything is working except when I generate the average number of heads and tails per trial, it comes out as 0 every time. the code for it is at the bottom, but I posted everything I did because I am not sure where the mistake is. How can I fix that? Thanks!!!!

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

} }`




Aucun commentaire:

Enregistrer un commentaire