Having some trouble with my number guessing game. The object is that the user thinks of a number between 1 and 100 and the computer tries to guess it in a set number of tries. The user inputs an "l" or an "h" if the guess is too low or too high, respectively. My problem is switching between the two. The first guess is always 50, so if that's too low it guesses 75. If that's too low, it guesses 88. Which works fine, except if you pick, let's say, 60. First guess 50. press "l" next guess 75, press "h" next guess is 37.
I've tried creating a new variable in order to reset the computer's guess each time through the loop but with no luck. Any help in the right direction would be appreciated.
Here's the code:
#include <iostream>
#include <string>
using namespace std;
const int NUMBER_OF_GUESSES = 5;
int main()
{
string firstName;
int computerGuess;
int numGuesses = 1;
char answer;
int max;
int min;
cout << "What is your first name?" << endl;
cin >> firstName;
cout << firstName << ", please think of a number between 1 and 100, and I will try to" << endl;
cout << "guess the number in 5 attempts." << endl << endl;
cout << "Press h if I've guessed too high or l if I've guessed too low." << endl << endl;
computerGuess = 50;
while (numGuesses <= 5)
{
cout << "Is the number " << computerGuess << "?" << endl;
cin >> answer;
if (answer == 'l')
{
max = 100;
min = computerGuess + 1;
computerGuess = (max + min)/2;
numGuesses ++;
}
else if (answer == 'h')
{
max = computerGuess - 1;
min = 0;
computerGuess = (max + 1)/2;
numGuesses ++;
}
}
return 0;
}