# C++ Question [Simple Guess My Number game]

## Recommended Posts

I made a guess my number game as it was simple , and being new to C++ was relatively easy to accomplish =D However i added a twist to it where the user inputs a number and the computer tries to guess it. But i've come across a problem.. The computer will guess numbers fine *using a randomly generated number* but as i dont know how to shrink the computers guess range after it guesses incorrectly. It just keeps guessing numbers *even repeats* until it finally happens upon the chosen number. Long story short lol , how can i make it so the computer will generate a random number in a smaller range after it guesses to high or to low? here's my code:
[SOURCE]
case 2:{
cout << "Ok, You pick a number and the Computer will try and guess it.\n\n";
Sleep(2000);
srand(time(0));

int playerNumber;
int computerTries = 0;
int computerGuess;

cout << "Enter a number between 1 and 10: ";
cin >> playerNumber;

do
{
computerGuess = rand() %10 +1;
cout << "The computers guess is: " << computerGuess <<endl;
++computerTries;
Sleep(500);
} while (computerGuess != playerNumber);

cout << "The computer guessed your number in " << computerTries << " guesses.\n\n";}
break;

}
[SOURCE/]

Thx for taking the time to read this and i appreciate any help given =)

~Skippy


##### Share on other sites
Just have two integers for upperGuess and lowerGuess and everytime generate a number between those two.

int lowerGuess = 1;
int upperGuess = 10;

...

do{
// generate a number between upper and lower guess
computerGuess = lowerGuess + rand() % (upperGuess - lowerGuess);

...

// update upper and lower guess
if ( computerGuess > playerNum ) upperGuess = computerGuess
else if ( computerGuess < playerNum ) lowerGuess = computerGuess

##### Share on other sites
Alright thanks, i thought of something like that , but i really didnt know how to implement it. Thanks a lot, much appreciated =D

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627743
• Total Posts
2978894

• 10
• 10
• 21
• 14
• 14