// Oldham, Jeffrey D. // 2000 Jan 31 // CS 3352 // Number of Heads Among Coin Tosses // Command-Line Argument // 1. number of trials #include #include // has EXIT_SUCCESS #include "rng.h" #include // has time() #include // for getpid() #include // for getpid() #include // has ULONG_MAX // Equilikely(a,b) returns a random integer in the range a, a+1, ..., b. template LONG Equilikely(const LONG & a, const LONG & b) { return a + static_cast((b-a+1)* Random()); } int main(int argc, char *argv[]) { if (argc != 2) { cerr << argv[0] << ": number-of-trials\n"; return EXIT_FAILURE; } unsigned long nuTrials = strtoul(argv[1], static_cast(0), 0); if (nuTrials == ULONG_MAX) { cerr << argv[0] << ": number-of-trials out of range\n"; return EXIT_FAILURE; } // Prepare the random number generator. // erroneous expression: PutSeed(time(static_cast(0)) ^ (getpid() << 15 + getpid())); PutSeed(time(static_cast(0)) ^ ((getpid() << 15) + getpid())); // Toss the coins. unsigned long nuHeads, trialNu; for (nuHeads = 0, trialNu = nuTrials; trialNu > 0; --trialNu) if (Equilikely(0,1) == 1) ++nuHeads; // Print the results. cout << "Number of trials:\t" << nuTrials << endl; cout << "Number of heads:\t" << nuHeads << endl; cout << "Fraction of heads:\t" << (nuHeads*1.0/nuTrials) << endl; return EXIT_SUCCESS; }