CodeLibrary/09_Clion_Cplus_work_20240620/function_02.cpp
2024-06-22 23:31:01 +08:00

30 lines
812 B
C++

#include <iostream>
using namespace std;
int guessNumber() {
int low = 1, high = 1000, mid;
while (low <= high) {
mid = low + (high - low) / 2;
cout << "Is the number " << mid << "? Enter 1 if it's smaller, 2 if it's larger, or 3 if correct: ";
int feedback;
cin >> feedback;
if(feedback == 1)
high = mid - 1;
else if(feedback == 2)
low = mid + 1;
else if(feedback == 3)
return mid;
else {
cout << "Invalid input. Please enter 1, 2, or 3." << endl;
continue;
}
}
return -1; // Should never reach here
}
//int main() {
// int guessedNumber = guessNumber();
// if(guessedNumber != -1)
// cout << "The number is: " << guessedNumber;
// return 0;
//}