I'm having trouble with the assignment below.
"Write a program that generates a random integer between 1-100 and then 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."
How do I make the random numbers work, and is there a better/more efficient way to write any parts? I'm still learning C++
Here's my code
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
// declare variables
int rightAnswer, userAnswer;
// determine rightAnswer
srand (time(NULL));
rightAnswer = (rand() % 100) + 1;
// begin the game
cout << "I'm thinking of a number between 1-100!" << endl;
do{
// collect data
cout << "Guess: ";
cin >> userAnswer;
// if else statements to determine correctness
if (userAnswer < 1 || userAnswer > 100)
cout << "The number is in the range 1-100. Try again!" << endl;
else if (userAnswer > rightAnswer)
cout << "Too high! Try again!" << endl;
else if (userAnswer < rightAnswer)
cout << "Too low! Try again!" << endl;
else
cout << "That's it! Good job!" << endl << ":)";
} while (userAnswer != rightAnswer);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire