Write a program that asks the user to guess a random number. The program should use a loop to prompt the user for the guess then display if the guess is 'too high' or 'too low'. In the end, display how many times it took to guess the number.
Use the attached template.
// Chapter 5 - Lab exercise, Random Number Guessing Game // // Name: // #include <iostream> #include <cstdlib> // Needed to use random numbers #include <ctime> // Needed to call the time function using namespace std; int main() { const int MAX_NUM = 100; // The maximum random value used unsigned seed; // "Seed" for the random number generator int secret, // The computer's randomly generated number guess; // The user's current guess // Seed the random generator and get a random integer between 1 and MAX_NUM seed = time(0); srand(seed); secret = rand() % MAX_NUM + 1; // Explain the game and get the user's first guess cout << "I am thinking of a number between 1 and " << MAX_NUM << ". \n"; cout << "Can you guess what it is? Enter your guess. "; cin >> guess; cout << endl; // Use a loop to prompt the user for the value of the secret number. Display // a message if the user's guess it too high or too low. Print how many guesses // were required to guess the number. return 0; }
// Chapter 5 - Lab exercise, Random Number Guessing Game // // Name: // #include <iostream> #include <cstdlib> // Needed to use random numbers #include <ctime> // Needed to call the time function using namespace std; int main() { const int MAX_NUM = 100; // The maximum random value used unsigned seed; // "Seed" for the random number generator int secret, // The computer's randomly generated number guess; // The user's current guess // Seed the random generator and get a random integer between 1 and MAX_NUM seed = time(0); srand(seed); secret = rand() % MAX_NUM + 1; // Explain the game and get the user's first guess cout << "I am thinking of a number between 1 and " << MAX_NUM << ". \n"; cout << "Can you guess what it is? Enter your guess. "; cin >> guess; cout << endl; // Use a loop to prompt the user for the value of the secret number. Display // a message if the user's guess it too high or too low. Print how many guesses // were required to guess the number. int count = 1; while(guess != secret){ if(guess > secret){ cout<<"Too high"<<endl; } else{ cout<<"Too low"<<endl; } cout << "Can you guess what it is? Enter your guess. "; cin>>guess; cout << endl; count+=1; } cout<<"Number of guesses = "<<count<<endl; return 0; }
Get Answers For Free
Most questions answered within 1 hours.