如何将rand()链接到while循环条件?

时间:2016-09-26 00:43:36

标签: c++

我正在制作一个简单的硬币翻转游戏,如果有意义,我不知道如何打印出结果。基本上我不知道该怎么做的条件,看看答案是真还是假。这是我到目前为止所拥有的。任何帮助将不胜感激

#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;
}

它假设看起来像example of finished product 这些是指南enter image description here

2 个答案:

答案 0 :(得分:0)

这是

#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;
}
祝你好运!

答案 1 :(得分:-1)

由于您将C ++作为languange,我强烈建议您查看现代(C ++ 11)随机引擎。

Here is a good sample