From 6d6aa263ae3b0d4bf3bea2aaf22f7a8275170932 Mon Sep 17 00:00:00 2001 From: Jesus Hilario Hernandez Date: Mon, 9 Dec 2019 10:55:20 -0600 Subject: [PATCH] added --- .../Programming Challenges/021.cpp | 60 +++++++++++++++---- 1 file changed, 50 insertions(+), 10 deletions(-) diff --git a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/021.cpp b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/021.cpp index c1a928d..35e80c3 100644 --- a/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/021.cpp +++ b/Chapter-5-Loops-and-Files/Review Questions and Exercises/Programming Challenges/021.cpp @@ -1,17 +1,15 @@ /******************************************************************** * -* 020. RANDOM NUMBER GUESSING GAME -* -* Write a program that generates a random number 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 should use a loop that repeats -* until the user correctly guesses the random number. +* 021. Random Number Guessing Game Enhancement +* +* Enhance the program that you wrote for Programming +* Challenge 20 so it keeps a count of the number of guesses +* that the user makes. When the user correctly guesses the +* random number, the program should display the number of +* guesses. * * Jesus Hilario Hernandez -* July 19th 2018 +* December 9th 2019 * ********************************************************************/ #include @@ -21,6 +19,48 @@ using namespace std; int main() { + const int MIN_VALUE = 1, + MAX_VALUE = 10; + + int random_num, + user_num; + + unsigned seed = time(0); + + srand(seed); + + + random_num = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; + cout << "Random number is: " << random_num << endl; + cout << endl; + + cout << "Guess a number between 1 and 10." << endl; + while(!(cin >> user_num)) + { + cout << "Error! A number must be entered: "; + cin.clear(); + cin.ignore(123, '\n'); + } + while(user_num != random_num) + { + if (user_num < random_num) + cout << "Your number is lower." << endl; + else + cout << "Your number is higher." << endl; + cout << "Try again: "; + + while(!(cin >> user_num)) + { + cout << "Error! A number must be entered: "; + cin.clear(); + cin.ignore(123, '\n'); + } + } + + cout << "\nCorrect! " << endl; + cout << "Random number = " << random_num << endl; + cout << "Your guess = " << user_num << endl; + cout << endl; return 0; }