Tossing Coins for a Dollar For this assignment, you will create a game program u
ID: 3832908 • Letter: T
Question
Tossing Coins for a Dollar
For this assignment, you will create a game program using the Coin class from Programming Challenge 12. The program should have three instances of the Coin class: one representing a quarter, one representing a dime, and one representing a nickel. When the game begins, your starting balance is $0. During each round of the game, the program will toss the simulated coins. When a coin is tossed, the value of the coins are added to your balance if they land heads-up. For example, if the quarter lands heads-up, 25 cents is added to your balance. Nothing is added to your balance for coins that land tails-up. The game is over when your balance reaches $1 or more. If your balance is exactly $1, you win the game. You lose if your balance exceeds $1. You can choose to walk away with your earnings at any point.
Turn in Coin.h and main.cpp.
Explanation / Answer
Here is the code for Coin.h:
#include <iostream>
#include <cstdlib>
class Coin
{
double coinValue;
public:
Coin()
{
coinValue = 0;
}
Coin(double value)
{
coinValue = value;
}
bool coinTossed()
{
return rand() % 2;
}
double getCoinValue()
{
return coinValue;
}
};
Here is the code for Main.cpp:
#include "Coin.h"
#include <iostream>
using namespace std;
int main()
{
//The program should have three instances of the Coin class:
//one representing a quarter, one representing a dime, and one representing a nickel.
Coin quarter (0.25);
Coin dime (0.10);
Coin nickel (0.05);
//When the game begins, your starting balance is $0.
double balance = 0;
while(balance <= 1)
{
// During each round of the game, the program will toss the simulated coins.
//When a coin is tossed, the value of the coins are added to your balance if they land heads-up.
//Nothing is added to your balance for coins that land tails-up.
if(quarter.coinTossed())
balance += quarter.getCoinValue();
if(dime.coinTossed())
balance += dime.getCoinValue();
if(nickel.coinTossed())
balance += nickel.getCoinValue();
//The game is over when your balance reaches $1 or more.
}
//If your balance is exactly $1, you win the game.
if(balance == 1)
cout << "You won the game..." << endl;
//You lose if your balance exceeds $1.
if(balance > 1)
{
cout << "You lost the game, and your balance is $0" << endl;
balance = 0;
}
}