I'm learning with a book and one of the excercises is to have the computer guess a number of which you think. My problem is that I need to keep altering the range which works for a couple tries then it seemingly forgets the range and goes on its own.

``````//Computer guesses your number

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main () {
char yourNumber;
int randRangeY = 100;
int randRangeX = 1;
int secretNumber = 1;
srand (time(NULL));

while(yourNumber != 'y')
{
if (yourNumber == 'h')
{
randRangeX = (secretNumber+1);
}
else if (yourNumber == 'l')
{
randRangeY = (secretNumber-1);
}

secretNumber = (rand()%randRangeY)+randRangeX;
cout << randRangeX << "," << randRangeY << endl;

cout << "Is it " << secretNumber << "? (h/l/y)" << endl;
cin >> yourNumber;

}

cout << "Awesome";
return 0;
}
``````

Thank you for your help :)

All 4 Replies

You should be guessing a number from randRangeX to randRangeY.

Instead, you're guessing from randRangeX to (randRangeX+randRangeY).

Guessing the middle of the range to make things faster. Using a random number in the range just adds extra complexity and extra guesses.

``````Is your number 50? L
``````secretNumber = (rand()%randRangeY)+randRangeX;
`secretNumber = (rand() % (randRangeY - randRangeX + 1)) + randRangeX`