我發現爲了讓猜測者猜到100
,我需要將最大值設置爲100
。我很困惑,因爲如果最大的東西是100
,那不包括100
?我的代碼有問題嗎?誰能解釋一下? Noob在這裏尋找一些幫助。非常感謝! 下面是代碼:爲什麼我需要將最大值設置爲101才能讓我的基本猜測程序猜到100?
#include <iostream>
using namespace std;
char yes_or_no;
int guess = 0;
void guesser(int we_are_on, int max, int min)
{
cin >> yes_or_no;
if (yes_or_no == 'y')
max = we_are_on;
else if (yes_or_no == 'n')
min = we_are_on;
else
cout << "Bad Input!\n";
cout << "Max: " << max << " Min: " << min << " Running Guess: " << we_are_on;
we_are_on = min + ((max-min)/2);
cout << "\nIs your number less than " << we_are_on << '?';
if (max - min <= 1)
{
guess = we_are_on;
return;
}
guesser(we_are_on, max, min);
}
int main()
{
cout << "Is your number less than 50?";
guesser(50, 101, 1);
cout << "\n Your number is " << guess;
return 0;
}
這聽起來像你可能需要學習如何使用調試器來遍歷你的代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver