Hi, so here is the code for a 'Guess My Number' game. But the 4th line up from the bottom confuses me. Surely the operator used should be == and not !=.
I thought the whole point is that the console outputs the "That's it!..." text when the user's guess is equal to the number. So why is the 'not equal to' operator used instead of ==. Or have I misunderstood the use of the 'while' statement?
It doesn't make any sense to me and yet the program runs perfectly. Please can someone explain why the program works? thanks.
// Guess My Number
// The classic number guessing game
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); //seed random number generator
int theNumber = rand() % 100 + 1; // random number between 1 and 100
int tries = 0, guess;
cout << "\tWelcome to Guess My Number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
if (guess > theNumber)
cout << "Too high!\n\n";
if (guess < theNumber)
cout << "Too low!\n\n";
}
while (guess != theNumber); // <-- LOOK HERE!
cout << "\nThat's it! You got it in " << tries << " guesses!\n";
oh nevermind lol I just realised why it works. Obviously the program is set to 'do' whatever it's meant to, as long as the 'while' statement is true. I thought the "while' statement was just the condition which determines whether the the bottom text is displayed or not. I guess I was thinking of it like an 'if' statement instead, which it isn't. If that makes sense