This is a problem from one of my classes called Guess the Number. We were to write a program that would generate a pseudo random number, and then let the user guess that number. The program required the following:
- Allow the user to guess a number
- Notify if the guessed number is high/low
- Use of pseudo random number generator
- Keep count of the number of guesses
- Loop through 10 times and determine average number of guesses
- Output for each game the average number of guesses made to guess the number
// *********************************************************************
// Description: Guess The Number
// *********************************************************************
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;
int main()
{
int number;
int guess;
int sum = 0;
int game = 0;
char choice;
fstream outFile;
do
{
int count = 0;
game++;
srand(time(NULL));
number = rand() % 100 + 1;
do
{
cout << "\nGuess an integer between 1-100: ";
cin >> guess;
cout << endl;
count++;
if (guess > number)
{
cout << guess << " is higher than the integer." << endl;
}
else if (guess < number)
{
cout << guess << " is lower than the integer." << endl;
}
else
{
cout << guess << " is the integer!" << endl;
outFile.open("GuessTheNumberOutput.txt", ios::out | ios::app);
outFile << number << " was the number, it took " << count
<< " guesses to get it right!\n";
outFile.close();
}
} while (guess != number);
cout << "\nDo you want to play another game (Y or N)? ";
cin >> choice;
sum += count;
} while (choice == 'Y' || choice == 'y');
outFile.open("GuessTheNumberOutput.txt", ios::out | ios::app);
outFile << "In " << game << " games it took an average of " << sum/float(game)
<< " guesses to get the correct number." << endl;
return 0;
}