20个问题游戏

20 Questions Game

本文关键字:游戏 问题 20个      更新时间:2023-10-16

我被指派用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",它也不会改变亚胺e。此外,如果第一个if语句回答了"n",它不会将imax也设置为相等。我已经为此挣扎了很长一段时间,非常感谢您的帮助。

您没有在循环中更改e的值,这就是为什么它在else条件下什么都不做的原因。你的逻辑也有点错误。试试这个,希望这会有所帮助:

#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;
cout << "Think of a number between 1-100." << endl; 
do
{
    int e = imin + ((imax - imin) / 2);
    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;
            break;
        }
        else
        {
            imin = e;
        }           
    }
    else
    {
        imax = e;
    }
} while (i == 0);

cout << "Your number is "<< i << endl;
system("PAUSE");
return 0;
} 

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<<". nn";
guess = ( high-low ) / 2;
while((high-low)!=1){
cout<<"Is your number less than or equal to "<<guess<<"? nEnter y or n. nn";
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;
}