I have a homework assignment I was hoping to get some light shed on...
Write a program that generates a random number between 1 and 100 and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” The program must use a loop that repeats until the user correctly guesses the random number or has made 10 guesses. The program needs to keep track of the number of guesses the user makes. At the end the program will display one of the messages in the table below based on the number of guesses the user took. The program must validate the user’s guess by making sure the value entered is between 1 and 100. If the value is not between 1 and 100, the user should be told to make another guess. The invalid input should not count as one of the 10 guesses the user is allowed.
Number of Guesses by the User Output Message
Less than 5 guesses "Either you know the secret or you got lucky!"
5-7 guesses "You're pretty good at this!"
8-10 guesses "You'll do better next time."
If guess 10 is not correct "Sorry - You have taken too many guesses."
Following is what I have coded thus far:
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
|
/**********************************************************************************************
COMMENTS
**********************************************************************************************/
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
// Variables used
const int MIN_NUM = 1;
const int MAX_NUM = 10;
int UserGuess; // Counter
int RightGuess = (rand() % 100) + 1;
int num = MIN_NUM;
do
{
cout << "Guess a number between 1 and 100: " << endl;
cin >> UserGuess;
if (UserGuess < 1 || UserGuess > 100)
cout << "The number is in the range 1 to 100. Guess again." << endl;
else if (UserGuess > RightGuess)
cout << "Too high! Try again!" << endl;
else if (UserGuess < RightGuess)
cout << "Too low! Try again!" << endl;
else
cout << "That's it! Way to go." << endl;
num++;
}
while (num <= MAX_NUM);
cin.ignore().get();
return 0;
}
|
I can see two things wrong with the code (although I'm sure others will see many more):
1: The code will loop through 10 iterations regardless of if the correct answer is chosen or not
2: Obviously, the code does not calculate a response based upon if the user guesses the correct answer in under 5, 7 or 10 guesses... I cannot think of a good way to accomplish this.
Any advice would be greatly appreciated.