fork(1) download
  1. #include <iostream>
  2.  
  3. using std::cin;
  4. using std::cout;
  5. using std::endl;
  6.  
  7. int main() {
  8. constexpr char yes = 'y';
  9. constexpr char no = 'n';
  10.  
  11. int left = 1;
  12. int right = 100;
  13.  
  14. cout << "Guess the number from " << left << " to " << right << "." << endl;
  15. cout << "Further enter \"" << yes << "\" if the answer is yes, or \"" << no << "\" if the answer is no." << endl;
  16.  
  17. while (right - left > 1) {
  18. int approximation = (left + right) / 2;
  19. cout << "Is your number less than " << approximation << "?" << endl;
  20.  
  21. char answer = ' ';
  22. while (true) {
  23. cout << ">>> ";
  24. cin >> answer;
  25. if (answer == yes || answer == no) {
  26. break;
  27. } else {
  28. cout << "I do not get it. Please, follow the above rule entering the answer." << endl;
  29. }
  30. }
  31.  
  32. switch (answer) {
  33. case yes:
  34. right = approximation;
  35. break;
  36. case no:
  37. left = approximation;
  38. break;
  39. default:
  40. break;
  41. }
  42. }
  43.  
  44. cout << "Your number is " << left << "." << endl;
  45. }
  46.  
Success #stdin #stdout 0s 5676KB
stdin
y
n
n
n
y
y
stdout
Guess the number from 1 to 100.
Further enter "y" if the answer is yes, or "n" if the answer is no.
Is your number less than 50?
>>> Is your number less than 25?
>>> Is your number less than 37?
>>> Is your number less than 43?
>>> Is your number less than 46?
>>> Is your number less than 44?
>>> Your number is 43.