Sign in to follow this  
skippydahobo

C++ Question [Simple Guess My Number game]

Recommended Posts

skippydahobo    122
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 this post


Link to post
Share on other sites
cabbar    127
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 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