English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

"Write a program that plays a guessing game where the computer tries to guess a number picked by the user. The program asks the user to think of a secret number, and then asks the user a sequence of guesses. After each guess, the user must report if it is too high or too low or correct. The program should count the guesses. (Hint: Maintain HighestPossible and LowestPossible variables, and always guess midway between the two. This is called a binary search.) Use only ifelse, while, do while coding, no fancy stuff and cout statements. The program output should look similar to:

Think of a number between 1 and 100 and press any key.
Is the number 50 (Correct, Low, High)? _h_
Is the number 25 (Correct, Low, High)? _h_
Is the number 13 (Correct, Low, High)? _l_
Is the number 19 (Correct, Low, High)? _c_
Number of guesses: 4
"

Underlined material is user input

2006-10-22 06:39:49 · 2 answers · asked by Anonymous in Computers & Internet Programming & Design

2 answers

//Necessary Header Files
#include
#include

//Variable Declarations
int Guesses, HighestPossible, LowestPossible, MyGuess, Range;
char PlayAgain = 'Y', HighLowCorrect;

//Begin Program Code
int main()
{
//Initiate While Loop For Game
while (PlayAgain == 'Y')
{
//Initialize Variables For Game Play
HighestPossible = 100;
LowestPossible = 0;
Guesses = 0;

//Display User Instructions
cout << "Please select a secret number between " << HighestPossible
<< " and " << LowestPossible << "." << endl;
cout << "I will try to guess your number as quickly as possible. For each"
<< endl;
cout << "guess please respond with either an H for too high, an L for too"
<< endl;
cout << "low, or a C for correct." << endl;

//Begin Guessing Loop
do
{
Range = HighestPossible - LowestPossible;
MyGuess = HighestPossible - int (Range/2);
cout << "Is the number " << MyGuess << "(High, Low, Correct)? ";
cin >> HighLowCorrect;
HighLowCorrect = toupper(HighLowCorrect);
if (HighLowCorrect == 'H')
HighestPossible = MyGuess;
if (HighLowCorrect == 'L')
LowestPossible = MyGuess;
Guesses = Guesses + 1;
} while (HighLowCorrect != 'C'); // End Do-While Loop

//Display Guess Count And See If User Wants To Play Again
cout << "It took me " << Guesses << " guesses." << endl;
cout << "Play Again? ";
cin >> PlayAgain;
PlayAgain = toupper(PlayAgain);
}; //End While
return 0;
} //End Program

2006-10-22 08:08:13 · answer #1 · answered by iuneedscoachknight 4 · 0 0

Dude try to solve your assignments yourself first ....... Ask if something confuses or troubles you

2006-10-22 06:47:21 · answer #2 · answered by Anonymous · 1 0

fedest.com, questions and answers