One of the exercises I found on this forum is to make a guessing game where the user thinks of a number and the computer has to get the right answer in seven or less guesses. I know how to get it in seven or less guesses, but I'm having trouble with what seems like a simple while loop
WARNING: this is a spoiler for one of the exercises found in the Articles forum. Don't look if you want to solve it yourself.
// Computer guessing game
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int getNum(int guess) {
unsignedint i = 1;
cout << "I guess " << guess << ". If that is correct, enter 1. If it's too high, enter 2. If it's too low, enter 3. ";
while (i && i < 4) {
cin >> i;
}
return i;
}
int main() {
srand(time(NULL));
int guess;
int count = 0;
int result;
bool hasWon = false;
while (!hasWon) {
cout << "Think of a number. The computer will guess, and you must answer (truthfully!) whether the guess is too high or too low.\n";
if (!count) {
guess = 50;
result = getNum(guess);
switch(result) {
case 1:
cout << "I win!\n";
hasWon = true;
break;
case 2:
cout << "Too high, eh?\n";
break;
case 3:
cout << "Two low, eh?\n";
break;
}
}
else {
switch(result) {
case 2:
guess /= 2;
break;
case 3:
guess += guess / 2;
}
result = getNum(guess);
}
++count;
}
}
The while loop on line 10 repeats endlessly, constantly asking for input. I'm frustrated that something as simple as a while loop is foiling me, but I can't figure out what's going wrong. I'm sure the answer is right there, could someone tell me what's wrong?