Advertisement
BLUuuE

Coin Flip - Single Loop w/ Average

Oct 8th, 2015
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. int 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 needed to get 9 heads: " << calls << endl;*/
  17.         return flips;
  18.     }
  19.     else
  20.     {
  21.         calls++;
  22.         coinFlip();     //call the function again...
  23.     }
  24. }
  25.  
  26. int main()
  27. {
  28.     srand(time(NULL));      //seed rand(), so we get a "random" number from it...
  29.  
  30.     //multithread();
  31.     unsigned int total = 0;
  32.     for (int i = 0; i < 100; i++)
  33.         total += coinFlip();
  34.     cout << "Number of trials needed: " << round(total / 100.0) << endl;
  35.  
  36.     cout << "Press enter to exit...";
  37.     getchar();
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement