Please use the [ code ] code [ /code ] tags when posting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void playGame(); //function prototype
int main()
{
playGame(); //function call
system("pause");
return 0;
}
void playGame() //Play function that asked for user input and determines if number is too high or too low from random number.
{
int guess, randomNum, numOfGuesses=0;
bool isGuessed;
char quit;
srand(time(NULL));
randomNum=rand() % 100 + 1;
isGuessed = false;
cout<<"Would you like to play a game? (y or n): ";
cin>>quit;
while(quit != 'N' && quit != 'n'){
cout<<"I'm thinking of a number between 1 and 100. Can you guess what number it is: ";
cin>>guess;
numOfGuesses ++;
do
{
if(guess < randomNum){
cout<<guess<<" is too low. Guess again. ";
cin>>guess;
numOfGuesses++;
}
else if(guess > randomNum){
cout<<guess<<" is too high. Guess again. ";
cin>>guess;
numOfGuesses++;
}
else if(guess == randomNum){
cout<<guess<<" is correct. You win and it only took you "<<numOfGuesses<<" tries"<<endl;
isGuessed = true;
}
}while((numOfGuesses < 6)&& (!isGuessed));
if(!isGuessed){
cout<<"You lose! The correct guess is "<<randomNum<<endl;
}
cout<<"Would you like to play again> (y or n): ";
cin>>quit;
while(quit != 'Y' && quit != 'y'){
cout<<"Thank you for playing!! "<<endl;
break;
}
}
}
|
Think about what you are doing when you restart a game.
You'll need to reset the guess count and get another random number.
On a game restart, you don't reset the guess amount. And you don't generate another random number.
Try making the loop bigger?
Hope this helps!
Edit:
You also don't need the while statement at the bottom, to cout the "Thanks for playing" message.
Simply use and if statement:
1 2 3 4
|
cin>>quit;
if(quit != 'Y' && quit != 'y')
cout<<"Thank you for playing!! "<<endl;
|
If a statement only contains
one line of code, you can simply add it under the statement without the use of: { and }
lol, and change the statement to:
if(quit != 'Y' || quit != 'y')
Note the && has changed to ||. If it is Y or y then you have
quit asked to play again.