Advertisement
BLUuuE

Coin Flip - Single Loop

Oct 8th, 2015
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. void coinFlip()
  2. {
  3.     static unsigned int calls = 0, total = 0;       //calls: number of times function has been called; total: accumulative total of flips
  4.     unsigned int sum = 0, flips = 0;    //sum: sum of H/T(H = 0, T = 1)
  5.  
  6.     do {    //flip the coin 9 times...
  7.         sum += (rand() % 2);    //H = 0, T = 1
  8.         flips++;
  9.     } while (flips < 9);
  10.  
  11.     total += flips;
  12.  
  13.     if (sum == 0)       //sum of 9 heads is 0, since H = 0
  14.     {
  15.         cout << "Total flips: " << total
  16.         << "\nNumber of trials to needed get 9 heads: " << calls << endl;
  17.     }
  18.     else
  19.     {
  20.         calls++;
  21.         coinFlip();     //call the function again...
  22.     }
  23. }
  24.  
  25. int main()
  26. {
  27.     srand(time(NULL));      //seed rand(), so we get a "random" number from it...
  28.  
  29.     //multithread();
  30.     coinFlip();
  31.  
  32.     cout << "Press enter to exit...";
  33.     getchar();
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement