/* * ----------------------------------------------------- * CS2S03/SE2S03, September 2011 * Assignment 2, Question 3 * File: PE0302.cpp * ----------------------------------------------------- * This program simulates flipping a coin repeatedly and * continues until three consecutive heads are tossed. * ----------------------------------------------------- */ #include "genlib.h" #include "simpio.h" #include "random.h" #include const int NUM_CONSECUTIVE_HEADS = 3; /* two sides of a coin */ enum sideT { head, tail }; /* Private function prototypes */ sideT FlipCoin(); int main() { int nConsecutiveHeads = 0; int nTrials = 0; Randomize(); while (nConsecutiveHeads != NUM_CONSECUTIVE_HEADS) { nTrials++; if (FlipCoin() == head) { cout << "heads" << endl; nConsecutiveHeads++; } else { cout << "tails" << endl; nConsecutiveHeads = 0; // reset } } cout << "It took " << nTrials << " flips to get "; cout << NUM_CONSECUTIVE_HEADS << " consecutive heads." << endl; return 0; } /* * Function: FlipCoin() * Usage: side = FlipCoin(); * ------------------------------------------------------------------- * * This function simulates flipping a coin. It returns head or tail 50 * percent of the time. * * ------------------------------------------------------------------- */ sideT FlipCoin() { return (RandomChance(0.50))? head : tail; }