简体   繁体   中英

Decision making with loops. Looking for a better way and understanding

I am trying to learn C++ from a book and online sources. After learning loops the book challenged me to create this simple number guessing game. After hours of trial and failure, which was fun of course. I did manage to complete the task, But looking back over the code and viewing other similar programs online. there appears to be a much shorter and more efficient way to accomplish this. For some reason I am really struggling with the logic here. I think I need more coffee as well. Below I have posted the program for viewing.

Overview:

Player 1 picks a number from 1 to 99.

Player 2 then has 3 chances to guess it correctly before the game ends.

int main()
{
    int num1 = 0, num2 = 0;
    
    int tries = 3;

    cout << "***Number Guessing Game***" << endl;
    cout << "Player 1 will pick a 1 to 2 digit number." << endl;
    cout << "Player 2 will have 3 chances to guess correctly." << endl << endl;

    while (num1 <= 0 || num1 > 99)
    {
        cout << "Player 1, please pick a number (1 to 99): ";
        cin >> num1;
    }

    system("cls");

    do
    {
        cout << "You have " << tries << " left." << endl;
        cout << "Player 2, pick a number (1 to 99): ";
        cin >> num2;
        tries--;

        if (num1 < num2 || num1 > num2)
        {
            cout << "Incorrect guess, try again!";
            system("cls");
        }
        else
        {
            system("cls");
            cout << "Your correct, you win!" << endl;
            break;
        }
    } while (tries != 0);

    if (tries == 0)
    {
        cout << "Too many attempts! Try again next time." << endl;
        cout << "Game Over";
    }
    else
        cout << "Game Over";
    
    system("pause>0");

}

Without changing the logic too much, since you're learning and need to make your experience, you could consider using a boolean:

int tries = 3;
bool found=false; 
...

You may then change your do/while to a while loop:

while (tries!=0 & !found)    // avoids adding some breaks
{
   ...
   found = num1==num2;
} 

You can then end your programme as follows:

if (found)
{
    system("cls");
    cout << "Your correct, you win!" << endl;
}
else {
    cout << "Too many attempts! Try again next time." << endl;
}
cout << "Game Over";   // common to the two

You need to think how to best bring in, in the while loop, the "try again" if there is another try, and the "wrong answer" if applicable. Ah; and do not clear the screen just after printing some message ;-)

The next structural improvement could be to use a for loop and keeping tries local to that loop. But maybe for a next chapter of your journey;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM