我已经完成了使用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语句。它会接受一个&#39; y&#39;并询问该号码是否为e,但是如果&#39; n&#39;得到回答它不会改变imin太e。如果&#39; n&#39;回答第一个if语句,它不会将imax设置为等于e。我已经在这方面苦苦挣扎了很长一段时间,非常感谢给予的任何帮助。
答案 0 :(得分:2)
您没有更改循环中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;
}
答案 1 :(得分:0)
#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;
}