QUESTION:
I'm trying to write a program to plays a number guessing game. The program currently gives the user as many tries need to guess the correct number. However I want the program to give the user no more than five tries to guess the number. Also, I want want my program to print a message, such as "You win!" or "You lose!" when the number is guess correctly or incorrectly.
I posted my sample code below with comment lines on the code lines I am having trouble with.
You should add a variable int guess_times = 0; and ++ it when the user makes a guess. In the while loop where the user enters input, put in the arguements
times<=5.
#include <iostream>
usingnamespace std;
int main() {
int numberOfGuesses = 0;
int guess;
while (numberOfGuesses != 5) // Limits the number of guesses to 5
{
cin >> guess; // user guesses
numberOfGuesses++; // add 1 to the guess variable. After 5 guesses
// it will be equal to 5 and quit the loop
}
return 0;
}
#include<iostream>
#include<random>
#include<ctime>
usingnamespace std;
int main(){
srand(time(0));
int num = rand() % 100;
int guess_times = 0;
int guess;
bool found = false;
while(guess_times<5){
cin>>guess;
if (guess>num){
cout<<"Your guess is higher, try again\n";
}
elseif (guess<num){
cout<<"Your guess is lower, try again\n";
}
elseif(guess==num){
found = true;
break; //stop the while loop
}
guess_times++;
}
if (found==false){
cout<<"You are out of guesses so you're out of the game, the number was "<<num;
}
elseif(found==true){
cout<<"You found the number!!!\n";
}
}
If you have any questions as to how the code works just asks
The program will never end unless you type in the number. I guess he is suggesting to put a variable int to keep track of the number of guesses the person types, otherwise it will just keep accepting more tries until the correct number is typed. Just make an int or short variable to keep track of the amounts of tries and put a loop that allows you to terminate the program if the number of guesses are equal to 5. you can do a for loop or while loop for that or add it to an existing loop.