In c++ I want to make number matching game. Conditions are these : 1. Excellent!
ID: 3842289 • Letter: I
Question
In c++ I want to make number matching game.
Conditions are these
:
1. Excellent! You guessed the number!
Would you like to play again (y or n)?
2. Too low. Try again.
3. Too high. Try again.
// Randomly generate numbers between 1 and 1000 for user to guess.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void guessGame(); // function prototype
int isCorrect(int, int); // function prototype
int main()
{
srand(time(0)); // seed random number generator
guessGame();
} // end main
// guessGame generates numbers between 1 and 1000 and checks user's guess
void guessGame()
{
int answer = 0; // randomly generated number
int guess = 0; // user's guess
char response = 'y'; // 'y' or 'n' response to continue game
// loop until user types 'n' to quit game
do
{
// generate random number between 1 and 1000
// 1 is shift, 1000 is scaling factor
answer = // 1) your codes
// prompt for guess
cout << "I have a number between 1 and 1000. "
<< "Can you guess my number? "
<< "Please type your first guess." << endl << "?";
cin >> guess;
// check the guess and compare with answer.loop until correct number
while (// 2) your codes)
cin >> guess;
// prompt for another game
cout << " Excellent! You guessed the number! "
<< "Would you like to play again (y or n)? ";
cin >> response;
cout << endl;
} while (// 3) your codes);
} // end function guessGame
// isCorrect returns true if g equals a
// if g does not equal a, displays hint
int isCorrect(int g, int a)
{
// guess is correct
//4) your codes. Check and return 1
// guess is incorrect; display hint. Too low. Try again or Too high. Try again.
//5) your codes. Check and return 0
} // end function isCorrect
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void guessGame();
bool isCorrect(int, int);
int main()
{
srand(time(0));
guessGame();
}
void guessGame()
{
int answer;
int guess;
char response;
do
{
answer = 1 + rand() % 1000;
cout << "I have a number between 1 and 1000. "
<< "Can you guess my number? "
<< "Please type your first guess." << endl << "? ";
cin >> guess;
while (!isCorrect(guess, answer))
cin >> guess;
cout << " Excellent! You guessed the number! "
<< "Would you like to play again (y or n)? ";
cin >> response;
cout << endl;
} while (response == 'y');
}
bool isCorrect(int g, int a)
{
if (g == a)
return true;
if (g < a)
cout << "Too low. Try again. ? ";
else
cout << "Too high. Try again. ? ";
return false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.