Write a program called that contains a secret number and gives the user three chances to guess that number. For each incorrect guess, your program must tell the user if the guess is too high or too low. The user can't guess more that three times and the user sees what guess they are.
Up above that is the description of the problem. My problem is that I cannot programme a pre picked number or determine the amount of guesses alloted and to tell them they didn't get it in the alloted amount.
#include<iostream>
using namespace std;
int main()
{
bool goOn=true;
while(goOn)
{
int number= ()%20+1;;
int guess;
int NumberOfGuesses;
char answer;
cout<<"Im thinking of a number between 1 to 20. Take a guess: ";
cin>>guess;
while(NumberOfGuesses <= 3)
{
if(guess>number)
{
cout<< guess << " is too high,Guess again: ";
cin>>guess;
NumberOfGuesses++;
}
if(guess<number)
{
cout<< guess << " is too low,Guess again: ";
cin>>guess;
}
}
if(guess==number)
{
cout<<"Congrats!! You got it.";
}
cout<<"would you like to play again? Enter y or n: ";
cin>>answer;
if(answer!='y')
{
goOn=false;
cout<<"thanks for playing!"<<endl;
}
}
return 0;
}
You need to clean your code up, create indentation so it is easier to read, and put comments.
Comments aren't really necessary for code this small, and the first thing you should do to clean up your code is add code tags. You get them from the first formatting button. They will make your code look like this:
1 2 3 4 5 6 7 8 9 10 11
#include<iostream>
usingnamespace std;
int main()
{
bool goOn=true;
while(goOn)
{
int number= ()%20+1;;
int guess;
int NumberOfGuesses;
. . .
You should actually use a for loop. Since you already have a pre determined number of tries, there is no need use a while loop. Once they take the last guess, place a cout statement that will display that they reached the limit. Since it is such a simple game, there really is no need for a bool statement. With that for loop, and the code inside of it, you should be good to go. So it should look some thing like this:
this program obviously doesn't have what guessing game has to have.You have to have a number that is different every time you play,so that you do not know what the answer is.That's why its called a guessing game.Use a random number generator to produce number.
#include <ctime>
using namespace std;
int random_integer(int min,int max)
{int random_integer;
random_integer = rand()%(max-min)+min;}
int main()
{
srand(time(0));//seed srand with time
<rest of the program> <- insert "random_integer(0,20);" without quotes in place of int number=5.
}