Consider the 19th guess. Lines 17-19 prompt for a guess and increment guessCount to 20. Let's assume the guess is too high, so line 24 prints "
Too High! "
Now the fun begins....
outOfGuesses is still false, so the loop runs again.
At line 16, guessCount is now 20, so guessCount < guessLimit is false. Line 21 executes, setting outOfGuesses to true.
Line 23 executes, but guess is still the old value, so it prints "
Too High!" again.
Control returns to the loop at line 15. outOfGuesses is true so the loop ends and the program goes to line 31. outOfGuesses is true so it prints "
You Lose!"
To fix this, get rid of variable outofGuesses and just check if guessCount<guessLimit in the while loop. This simplifies the code.
Note also that I changed line 8 to call srand(). In your original code, you actually declared a local int variable called srand and initialized it to the value of time(0). This is one of the failings of C++ syntax: sometimes a simple misstatement creates valid code that doesn't mean anythink like what you intended.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int secretNum = rand();
int guess;
int guessCount = 0;
int guessLimit = 20;
while(secretNum != guess && guessCount < guessLimit) {
cout << "Guess: ";
cin >> guess;
guessCount++;
if(guess > secretNum ){
cout << "Too High! ";
} else if( guess < secretNum){
cout << "Too Low! ";
}
}
if(guessCount >= guessLimit) {
cout << "You Lose!";
} else {
cout << "You Win !";
}
return 0;
}
|