Its the rng guessing game. When I run the code it seems like work properly.
However, It just ends some times when i put the number below the rng created.
for example, if the rng number was 35, when I put 34, it just ends. Please help me
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
// Program starts here:
int main()
{
constint MIN_VALUE = 1;
constint MAX_VALUE = 100;
int num1, num2, counter = 1; //counter = 1 because you always need to try at least once to get the correct number.
srand(time(NULL)); //change the random number everytime it runs
num1 = rand() % (MAX_VALUE - MIN_VALUE + 1) + MIN_VALUE; //num 1 is random number between 1 to 100
cout << num1;
//do-while loop used to intruct user to put correct number
do {
cout << "Number should be between 1 to 100" << endl;
cout << "input your number" << endl;
cin >> num2;
} while (num2 < 1 || num2 > 100);
//When user did correct guess prints out good job and shows the number of guess
if(num2==num1){
cout << "Good Job" << endl;
cout << "trials:" << counter << endl;
}
// two while loop giving clues to the user.
// every time user enters the while loop, counter goes up
else {
while (num1>num2){
cout << "Too low, try again." << endl;
cin >> num2;
counter++;
}
while (num1<num2){
cout << "Too high, try again." << endl;
cin >> num2;
counter++;
}
}
return 0;
}
This loop was after your other loop. It checks if your guess was too high. What happens if your guess is too low? It skips this loop. Does it go back to the loop before it to check if the number is too low? No, it doesn't.
Those two loops should not be loops. Change them to if statements. Then put both if statements inside a single loop that will run until the user guesses the answer.
It will run at that point, but obviously you will want to move the if(num2==num1) stuff to after the new loop.
It runs forever because you duplicated the conditions on the lines I mentioned.
What happens if you guess too small? You don't have anything to handle that. You don't ask for a new un so it's always un!=rn, giving you the infinite loop.