Hey, so I've created a random number game where you are supposed to guess the number. The only problem is I want the user to only have five guesses, but I can't figure out how to do that. Any suggestions? (By the way, the program as of right now is set to print what the number is, that is just so that I know it works)
#include <iostream> /*included to allow for cout/cin to be used*/
#include <ctime> /*included to allow time() to be used*/
#include <cstdlib> /*include to allow rand() and srand() to be used*/
usingnamespace std;
int main() {
bool cont=true;
while(cont)
{
int count=0;
int guess;
srand(time(0)); /*seeds random number generator. Do this just once*/
int x = rand() % 50;
cout << "I'm thinking of a number between one and fifty. You have five tries. Go.";
cout << "\nx = " << x << endl;
std::cin >> guess;
while (guess !=x) {
{
if (guess > x) {
cout << "Too high! Try again. ";
cin >> guess;
}
if (guess < x) {
cout << "Too low! Try again. ";
cin>>guess;
}
if (guess == x) {
cout << "You're exactly right! Good job! \n"; return 0;
}
}
}
}
return 0;
}
Do you initialize count to 0 before entering the loop?
e: oh nevermind. You should get a new guess at the beginning of the loop. You're getting new guesses in the middle of the loop. (cin >> guess;). And the way you handle it (if, if, if, instead of if, else if, else if.) it's possible to have a guess that's higher than x, then one that's lower than x, in one single loop.
Oh okay that actually helped a lot. I switched it around and put the guess at the start of the loop, and changed it from all if's to if, else if, else if. Thank you very much!