CoinTossSimulator.cpp
CoinTossSimulatorDm.cpp
CoinTossSimulator.h
/* CoinTossSimulator.h - Specification file for the Coin class. */
#ifndef COIN_TOSS_SIMULATOR_H
#define COIN_TOSS_SIMULATOR_H
#include <string>
class Coin
{
private:
std::string sideUp; // The side of the coin facing up
int cntHeads; // Holds the count for heads
int cntTails; // Holds the count for tails
public:
Coin::Coin() : sideUp(""), cntHeads(0), cntTails(0) // Constructor
{
initRNG();
toss();
sideCount();
}
void initRNG(); // Initializes the random number generator
void toss(); // Performs a coin-toss
void sideCount(); // Counts the number of times heads or tails is facing up
std::string getSideUp() const
{ return sideUp; }
int Coin::getCntHeads() const
{ return cntHeads; }
int Coin::getCntTails() const
{ return cntTails; }
};
#endif
CoinTossSimulator.cpp
/* CoinTossSimulator.cpp - Implementation file for the Coin class. */
#include <cstdlib>
#include <ctime>
#include "CointTossSimulator.h"
/* **********************************************************
Coin::initRNG()
This function initializes the RNG.
********************************************************** */
void Coin::initRNG()
{
srand((unsigned int)time(NULL));
}
/* **********************************************************
Coin::toss()
This function determines the coin side facing up after
each toss. The side facing up is assigned to the sideUp
member variable.
********************************************************** */
void Coin::toss()
{
const int HEADS = 1;
const int TAILS = 2;
unsigned int sides = 0;
sides = HEADS + rand() % TAILS;
if (sides == HEADS)
{
sideUp = "Heads";
}
else
{
sideUp = "Tails";
}
}
/* **********************************************************
Coin::sideCount()
This function uses a ternary operator to count the number
of times 'heads' and 'tails' are facing up.
********************************************************** */
void Coin::sideCount()
{
sideUp == "Heads" ? cntHeads++ : cntTails++;
}
CoinTossSimulatorDm.cpp
/* CoinTossSimulatorDm.cpp - This program demonstrates the Coin class. */
#include <iomanip>
#include <iostream>
#include <string>
#include "CointTossSimulator.h"
using std::cout;
using std::cin;
int main()
{
Coin coinToss;
const int NUM_TOSSES = 20;
cout << "\t\tCOIN TOSS SIMULATOR\n\n";
cout << "I will now perform an initial toss.\n\n";
cout << "The side facing up is: " << coinToss.getSideUp() << "\n\n";
cout << "I will now toss the coin " << NUM_TOSSES << " times.";
cout << "\n(Press a key to continue)\n";
cin.ignore();
for (int i = 0; i < 20; i++)
{
coinToss.toss();
coinToss.sideCount();
cout << "Toss #" << std::setw(2) << (i + 1) << ": "
<< std::setw(18) << coinToss.getSideUp() << "\n";
}
cout << "\nThe number of times 'Heads' was facing up: " << coinToss.getCntHeads() << "\n";
cout << "The number of times 'Tails' was facing up: " << coinToss.getCntTails();
cout << "\n\nThis program will now exit. Have a nice day!";
cin.ignore();
return 0;
}
No comments:
Post a Comment