In: Computer Science
Enter the left end and right end of a range of integers. User chooses an integer in that range. Computer makes a guess that equals the mid of the range. User gives a feedback for each guess: 1 for too big, 2 for too small and 3 for just right. When the feedback is 1 (too big), the computer throws away any integer that is bigger than guess. When the feedback is 2 (too small), the computer discards the integers any integers that is smaller than the guess. When computer makes a correct guess, the game ends. In C++
Note that your code must ensure a user to entre a feedback in [1, 3].
Sample input/output:
Enter left end in range: 0
Enter right end in range: 10
User has an int in [0, 10]. Computer will guess.
guess #1: 5. How is my guess?
1. too big 2. too small 3. just right
Enter only 1, 2, or 3: 2
guess #2: 8. How is my guess?
1. too big 2. too small 3. just right
Enter only 1, 2, or 3: 1
guess #3: 6. How is my guess?
1. too big 2. too small 3. just right
Enter only 1, 2, or 3: 2
guess #4: The answer must be 7.
C++ code screenshot:
C++ code:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int left, right, guessNumber = 1, mid, choice;
cout << "Enter left end in range: ";
cin >> left;
cout << "Enter right end in range: ";
cin >> right;
cout << "User has an int in [" << left << ", " << right << "]. Computer will guess.\n";
while (left < right)
{
mid = (left + right) / 2;
cout << "guess #" << guessNumber << ": " << mid << ". How is my guess?\n";
cout << "1. too big 2. too small 3. just right \n";
cout << "Enter only 1, 2, or 3: ";
cin >> choice;
while (cin.fail() || choice < 1 || choice > 3)
{
//something went wrong, we reset the buffer's state
cin.clear();
//and empty it
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "\nINVALID INPUT !!! \n";
cout << "Enter only 1, 2, or 3: ";
cin >> choice;
}
if (choice == 3)
{
cout << "\n\nThank You for playing...\n";
return 0;
}
else if (choice == 1)
{
right = mid - 1;
}
else
{
left = mid + 1;
}
guessNumber++;
}
cout << "guess #" << guessNumber << ": The answer must be " << left << ".\n";
return 0;
}
Output 1:
Output 2: