Misunderstanding Little Game Project Assignment C++ (end of first section)

Well Ivan had the example from two players but I automatically assumed that the computer would ask the user to guess a number from a randomly generated number. In Pascal you have to first make sure you call Random or the numbers generated will not have sufficient entropy. So I googled the C++ equivalent and it gives similar warnings about the number not being random enough. Requires #include <>cstdlib

#include

using namespace std;
#include <>cstdlib

int main()
{
int ARandomNumber = rand();
int AGuess;
cout << “The computer has chosen a number. Try to guess it.” << endl;
cin >> AGuess;

int NumberOfGuesses = 1;
while (AGuess != ARandomNumber)
{
    if (AGuess < ARandomNumber)
    {
        cout << "Your guess of " << AGuess << " is too low. Try again" << endl;
        cin >> AGuess;
    } else
    if (AGuess > ARandomNumber)
    {
        cout << "Your guess of " << AGuess << " is too high. Try again" << endl;
        cin >> AGuess;
    } else
    {
        break;  // game is over!
    }

    NumberOfGuesses++;
}
cout << "Congratulations, the number is "<< ARandomNumber<< ". It took " << NumberOfGuesses << " to get it correct." << endl;
return 0;

}

1 Like

I did the assignment a bit differently, while(guess != number) instead of while(true)

The game seems to work!

1 Like

Now that I think of it, my original code doesn’t take into consideration what happens when the first guess is correct.

One thing that I had to look up to make the game usable was a way to hide the initial guess from player 2.

I put 50 blank lines after player 1 submits their guess. I don’t think it is the best solution but it will do for now:

cout << “Player 1, enter a number:” << endl;
int number = 0;
cin >> number;
cout << string(50, ‘\n’);

1 Like