Interval for random numbers

Jul 26, 2012 at 11:07am
Hi. I have encoutered a problem, I wasnt able to solve. I wanted to make a program, that guesses the number I have guessed between 1 and 100. I write "high" and "low" till it eventually gets the number. The only problem is, that when after a "low" I write "high", it forgets the numbers it was supposed to exclude, therefore it never gets the number right. Here is the code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <time.h>

using namespace std;

int main ()
{
unsigned int i, j;
string mystring;
srand ( time(NULL) );
i = rand () % 99 + 1;
j = 0;
do {
cout << "Is the number " << i <<" ?\n";
cin >> mystring;
if (mystring == "low")
{
j = 100 - i;
srand ( time(NULL) );
i = rand () % i + j;
}
if (mystring == "high")
{
srand ( time(NULL) );
i = rand () % i;
}

} while (mystring != "yes");
getline (cin, mystring);
}
Jul 26, 2012 at 11:10am
How about creating upper and lower markers and using them in the random number generation? Then, you can set the markers according to whether it's low or high.

Effectively, this is a binary search. You may want to take a look at them.

As a note, you should only seed the random number once.
Jul 26, 2012 at 8:17pm
Thanks for the response, I will look into it.
Topic archived. No new replies allowed.