Erik Sandoval Erik Sandoval - 2 months ago 11
C++ Question

How to link rand() to a while loop condition?

I'm making a simple coin flip game and i'm not sure how to get it to print out a result if that makes sense. basically I'm not sure what to make the while condition to see if the answer is true or false. here is what i have so far. any help would be appreciated

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
srand(static_cast<unsigned int>(time(0)));
char answer;
int bank = 10;
int guess;
int h = 0;
int t = 1;

cout << "Welcome to the coin flip game. It cost a dollar to play." << endl;
cout << "If you guess correctly you will will $2.00" << endl;
cout << "Do you want to play <y/n>" << endl;
cin >> answer;
int flip = rand() % 3;
guess = flip;
while (toupper(answer) == 'Y')
{
cout << "Your bank is $" << bank << endl;
cout << "Enter heads or tails <h/t>" << endl;
cin >> guess;

while (guess == h)
{
bank++;
cout << "Winner, the flip came up " << flip << endl;
cout << "Would you like to play again <y/n>?" << endl;
cin >> answer;
}

}

return 0;
}


its suppose to look like this example of finished product
and these are the guidelines enter image description here

Answer

Here goes-

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand(static_cast<unsigned int>(time(0)));
    char answer;
    int bank=10;
    char guess;
    char result;
    cout << "Welcome to the coin flip game. It cost a dollar to play." << endl;
    cout << "If you guess correctly you will will $2.00" << endl;
    cout << "Do you want to play <y/n>" << endl;
    cin >> answer;
    while (toupper(answer) == 'Y')
    {
        bank--;
        cout << "Your bank is $" << bank << endl;
        cout << "Enter heads or tails (h/t)" << endl;
        cin >> guess;
        if(rand()%2==1)
            result='t';
        else
            result='h';
        if(guess==result)
        {
            bank+=2;
            cout << "Winner, the flip came up ";
        }
        else
            cout << "Sorry, you lose. The coin flip came up ";
        if(result=='t')
            cout << "Tails" << endl;
        else
            cout << "Heads" << endl;
        cout << "Would you like to play again (y/n)?" << endl;
        cin >> answer;
    }

    cout << "Thanks for playing, your bank is $" << bank << endl;

    return 0;
}

Good luck!