Number guessing

I'm currently learning c++ from "Beginning C++ through game programming"
One of the exercises was to edit a program to have the computer guess your number instead of you guessing the computer's number. This is what I have so far

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051`` ``````// Guess My Number // The classic number guessing game #include #include #include using namespace std; int main() { srand(static_cast(time(0))); //seed random number generator int compGuess = rand() % 100 + 1; // random number between 1 and 100 int tries = 0; int answer; bool guess; cout<<"\tWelcome to Guess your Number!\n"; cout<<"\tThink of a number between 1 and 100.\n\n"; do { cout<<"My guess is "<>answer; ++tries; guess = false; if (answer == 2) //If answer is too high { compGuess = rand() % compGuess + 1; } else if (answer == 1) //If answer is too low { compGuess = rand() % compGuess + compGuess + 1; } else if (answer == 3) { cout<<"I win! It only took me " << tries << " guesses!\n"; guess = true; } }while(!guess); }``````

The program works in that if it guessed too low, it will guess a higher number and if it guessed too high it will guess a lower number. The problem is it will guesses completely random numbers below or above the previous number.

My question is this:
a) Is there a way to make it guess based off of previous guesses?
b) Is there a better way of limiting the range of the rand() than the module?
Last edited on
@Fovv

Create a couple more variables. `int lo = 0; hi = 100;` When the computer guesses, and the guess was to high, assign variable hi, to that guess, and the same if the guess was to low. Then the computer guess would be `compGuess = rand() % (hi-low+1)+low;`
@whitenite1

Thank you very much for the help. The program works as intended :D
Topic archived. No new replies allowed.