Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                                                                                            
                
        
我得到的任务是用C ++编写代码,其中用户必须猜测一个介于1到100之间的数字,然后计算机会有20个问题来尝试猜测这个数字。这是我编写的代码:

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
int imax;
char ans;
int imin;
int i;
const char y = 'y';
const char n = 'n';



imax = 100;
imin = 0;
i = 0;
int e = (imax - imin) / 2;

cout << "Think of a number between 1-100." << endl;

do
{
    cout << "Is the number equal or greater too " << e << endl;
    cin >> ans;
    if (ans == y)
    {
        cout << "Is the number " << e << endl;
        cin >> ans;
        if (ans == y)
        {
            i = e;
            return i;
        }
        else
        {
            imin = e;

        }
    }
    else
    {
        imax = e;
    }

} while (i == 0);



cout << "Your number is "<< i << endl;

system("PAUSE");

return 0;
}


该代码会一直工作到到达第二个if语句为止。它将接受“ y”并询问数字是否为e,但如果回答“ n”,则也不会更改imin e。同样,如果第一个if语句的答案为“ n”,则它也不会将imax设置为等于e。我已经为此苦苦挣扎了很长时间了,非常感谢您给予的任何帮助。

最佳答案

EE 273是一场噩梦。我在其他地方找到了此代码:

#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;
}

09-27 05:20