From Wikipedia, the free encyclopedia
- This is the text of a C++ source code, meant to have a ".cpp" file extension. To run the program, one will need a program to compile and link the code.
#include <iostream>
using namespace std;
void main()
{
int Guess = 50;
int Hi = 101;
int Lo = 0;
int Counter = 0;
int Right = 0;
char Answer;
cout << "Think of a whole number between 0 and 100.\nTell me 'h' if I guess too high,";
cout << " and 'l' if I guess too low.\nTell me 'r' when I get it right.\n";
do
{
cout << "Is the number " << Guess << "? ";
cin >> Answer;
switch(Answer)
{
case 'h':
Hi = Hi - (Hi - Guess);
Guess = (Hi + Lo) / 2;
Counter++;
break;
case 'l':
Lo = (Guess - Lo) + Lo;
Guess = (Hi + Lo) / 2;
Counter++;
break;
case 'r':
Right = 1;
Counter++;
break;
default:
cout << "Invalid entry." << '\n';
break;
}
} while (Right == 0);
cout << "Yes, I knew it was somewhere around that.\nIt took me " << Counter;
cout << " guesses to get it right. Thanks for playing!\n";
cin.ignore();
}