我正在使用 C++ 解决文本原则和实践中的一些问题,我遇到的具体问题如下。用户必须想出一个介于 1 到 100 之间的数字,然后计算机将通过一系列猜测找出问题所在。
当前代码除数字 1 外都有效(由于除以 2 时整数舍入)。我似乎想不出办法来解决这个问题。
这是当前的源代码:
#include <iostream>
using namespace std;
const int MAX_VALUE = 100;
const int MIN_VALUE = 1;
int guess;
int high = MAX_VALUE;
int low = MIN_VALUE;
char choice;
int main(){
cout<<"Think about a number between "<<MIN_VALUE<<" and "<<MAX_VALUE<<". \n\n";
guess = ( high-low ) / 2;
while((high-low)!=1){
cout<<"Is your number less than or equal to "<<guess<<"? \nEnter y or n. \n\n";
cin>>choice;
if(choice=='y' || choice=='Y') {
high = guess;
guess -= ( high - low ) / 2;
}
else if(choice=='n' || choice=='N') {
low = guess;
guess += (high - low ) /2;
}
else cout<<"Incorrect choice."<<endl;
}
cout<<"Your number is: "<<high<<".\n";
system("pause");
return 0;
}