Sign in to follow this  

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:
case 2:{
			cout << "Ok, You pick a number and the Computer will try and guess it.\n\n";

			int playerNumber;
			int computerTries = 0;
			int computerGuess;

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

				computerGuess = rand() %10 +1;
				cout << "The computers guess is: " << computerGuess <<endl;
			} while (computerGuess != playerNumber);
			cout << "The computer guessed your number in " << computerTries << " guesses.\n\n";}


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


Share this post

Link to post
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;


// 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 this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this