Hi all first thank you for taking the time to read this I really appreciate the help.
What my question is im trying to make is a little console game (teaching myself c++) that the computer tries to guess a number you type in. im not sure whats wrong with my code, sometimes its works but the number the computer guesses never changes. Is there something I'm doing wrong or missing??
//Guess My Number
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
int tries
int Playernumber;
int toolow = 1;
int toohigh = 10;
srand(time(0));
int Compguess = rand() % toohigh + toolow; // A random number between 1-10
cout << "\tWelcome to Guess My Number\n\n";
cout << "/tType in your number: ";
cin >> Playernumber >> //player types in number for computer to guess
//Now creating the loop the thoughts for this was so that the computer would never
//choose a number that has already been choosen
do
{
int Compguess = rand() % toohigh + toolow;
cout << "Computer Guesses: "<< Compguess <<"\n\n";
++tries
if (Playernumber > Compguess)
{
cout << "Too High!\n\n";
toohigh = Compguess;
}
elseif (Playernumber < Compguess)
{
cout << "Too Low!\n\n";
toolow = Compguess;
}
else
{
cout << "\nThats it! The Computer wins and it took " << tries <<" guesse(s)!\n";
}
} while ( Playernumber != Compguess);
return 0;
}
It seems that you attempt to narrow down the range lines 45 and 52. That has logical errors.
Lets say that hi=10 and lo=3. Random number is thus in [3..12].
This time, the guess is 7 and that is too low. Logically, you should next look from [8..12].
However, you code sets lo=7 and hi remains 10. The next number will be from [7..16].
You should have adjusted both lo and hi.
What if 7 was too high? You set hi=7, so the new range is [3..9]. It was enough to change the hi, but how to do it wisely?
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
srand(time(0)); // seed random number
int tries = 1;
int Playernumber;
int Compguess = rand() % 10 + 1; // initialized
cout << "\tWelcome to Guess My Number\n\n";
//Now creating the loop the thoughts for this was so that the computer would never
//choose a number that has already been choosen
do
{
cout << "Type in your number: ";
cin >> Playernumber; //player types in number for computer to guess
Compguess = rand() % 10 + 1; // random number 1-10
cout << "Computer Guesses: " << Compguess << "\n\n";
if (Playernumber > Compguess)
{
cout << "Too High!\n\n";
++tries;
if (tries > 5)
{
cout << " computer lose\n";
cin.get();
cin.get();
return 0;
}
}
elseif (Playernumber < Compguess)
{
cout << "Too Low!\n\n";
++tries;
if (tries > 5)
{
cout << " computer lose\n";
cin.get();
cin.get();
return 0;
}
}
else
{
cout << "\nThats it! The Computer wins and it took " << tries << " guesse(s)!\n";
}
} while (Playernumber != Compguess);
cin.get();
cin.get();
return 0;
}
I guess this is what you mean.
I took away 2 variables
and move the Player input in the do-while loop