I am trying to make a program in which the computer guesses the number you are thinking of by guessing a random number (between 1 and 100) and then you telling it whether the guesses are high or low. While the computer's guess do decrease when I input "high", they do not increase consistently (they might increase once, and then decrease again) when I input "low". My calculations seem to be right, so does this have more do with a do-while loop being within an if statement?
Thanks in advance.
[using namespace std;
int main(int argc, char *argv[])
{ srand(0);
string str;
int min=1;
int max=100;
int range=(max-min)+1;
int guess=rand()%(range)+1;
cout<<"Think of a number between 1 and 100 and I will guess it."<<endl;
cout<<guess<<"\n";
cout<<"Is this right?"<<endl;
cin>>str;
if (str=="right")
cout<<"Joe is cool."<<endl;
else if (str=="wrong")
{do
{
cout<<"Was it high or low?\n";
cin>>str;
if (str=="high")
range=guess-1;
else if (str=="low")
range=guess+1;
guess=rand()%(range);
cout<<guess;
cout<<"\nIs this right?"<<endl;
cin>>str;
When the answer "high" or "low" is given, the program adjusts the value of range. However, it should instead be modifying either max or min. After that, range needs to be re-calculated and the random number generated accordingly so that the new guess is somewhere between max and min.
Let's say min = 1 and max = 100
after a guess of 7, and a response of "low", you will now have min = 8, max = 100.
range=max-min; will give range = 92.
and guess=rand()%(range); will generate a number between 0 and 91 (but it should be between 8 and 100).
Where's the problem?
Look at the code used at the start:
1 2
int range=(max-min)+1;
int guess=rand()%(range)+1;
this gives the correct result, but for the wrong reason. It should actually be:
1 2
int range=(max-min)+1;
int guess=rand()%(range)+min;
and you can use these same two expressions to recalculate the range and generate the guess later in the program too.