Pages

Friday, 19 August 2016

Chapter 5 Exercise 40, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

5.40 (Simulation: heads or tails) Write a program that simulates flipping a coin one million times and displays the number of heads and tails.

public class ProgrammingEx5_40 {
 
 public static void main(String[] args) {
  int c = 0;
  int h = 0;
  int t = 0;
 
  for (int i = 0; i < 1e6; i++) {
   c = (int) (Math.random() * 2);
    
   if (c == 1) {
    h++;
   } else {
    t++;
   }
 
  }
   
  System.out.println("The number of heads is " + h);
  System.out.println("The number of tails is " + t);
 }
 
}

No comments :

Post a Comment