• Advertisement
Sign in to follow this  

C++ Question [Simple Guess My Number game]

This topic is 3859 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Alright thanks, i thought of something like that , but i really didnt know how to implement it. Thanks a lot, much appreciated =D

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement