I've been having trouble with creating this... You're supposed to pick a number and the computer has to guess it. So far it's working, but I can't figure out why the computer won't obey the continue when it guesses over or below what it's already guessed. Can anyone help?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <Windows.h>
usingnamespace std;
int main()
{
cout<<"Write a new version of the Guess My Number program in which the player and the"
<<" computer switch roles. That is, the player picks a number and the computer must guess what it is.\n\n";
cout<<"\tWelcome to Guess my Number\n\n";
int myNumber;
while(true)
{
cout<<"Pick a number, between 1 and 100, for the computer to guess: ";
cin>>myNumber;
if(myNumber >= 1 && myNumber <= 100)
{
break;
}
cout<<"The number wasn't between 1 and 100... Try again.\n\n";
}
srand(static_cast<unsignedint>(time(0)));
int computerNumber = (rand()%100)+1;
int lowestNumber = 0;
int highestNumber = 100;
int tries = 0;
while(computerNumber != myNumber)
{
if(computerNumber < myNumber)
{
lowestNumber = computerNumber;
computerNumber += (rand()%(100))+1;
}
else
{
highestNumber = computerNumber;
computerNumber -= (rand()%(100))+1;
}
if(computerNumber <= lowestNumber || computerNumber >= highestNumber)
{
continue;
}
cout<<"\nThe computer Guesses: "<<computerNumber<<endl;
++tries;
Sleep(500);
}
cout<<"\nThe computer guessed your number in only "<<tries<<" tries!\n\n";
return 0;
}
You can get rid of the continue statement and that whole if block. It does nothing. The error in your program is here:
1 2 3 4 5 6 7 8 9 10 11
if(computerNumber < myNumber)
{
lowestNumber = computerNumber;
++computerNumber; //Changing to this from computerNumber += (rand()%(100))+1;
}
else
{
highestNumber = computerNumber; //Changing to this from computerNumber -= (rand()%(100))+1;
--computerNumber;
}
Now the program will work, but will take a lot of tries to get the number. The trouble with constantly adding a rand() to your total is that the computer is guessing numbers out of range and also just firing randomly into a dark room, hoping to get an answer. You can use some simple if/else to improve the search the computer does, for example: