作为一项练习,我试图制作一个计算机试图猜测我正在考虑的数字的程序。我能够让它在一般情况下进行随机猜测,但我希望能够通过记录它的最高和最低猜测并在这些猜测之间进行新的猜测,使其能够更快地猜出正确的数字。
例如,如果计算机猜测20然后是40,那么它的第三次猜测应该只在20到40之间。这是否可能,如果是这样,我做错了什么? #包括 #包括 #包括 使用namespace std;
int main()
{
string yesOrNo;
string lowOrHigh;
srand(time(NULL));
int random_number = 1+(rand() % 100);
int lowGuess(0);
int highGuess(100);
int guessAttempts(1);
int adjustMinMax(int random_number, int& highestGuess, int& lowGuess, string lowOrHigh);
int adjustGuess(int& random_number, int lowGuess, int highestGuess);
cout << "Think of a random number between 1 and 100 in your head.";
cout << endl << "Guesses Attempted: " << guessAttempts;
cout << endl << "Is your number " << random_number << "?";
cout << endl << "y/n: ";
cin >> yesOrNo;
while (yesOrNo == "n" || yesOrNo == "no")
{
++guessAttempts;
cout << endl << "Was my guess too high or too low l/h? ";
cin >> lowOrHigh;
adjustMinMax(random_number, highGuess, lowGuess, lowOrHigh);
adjustGuess(random_number, lowGuess, highGuess);
cout << "Guesses Attempted: " << guessAttempts;
cout << endl << "Is your number " << random_number << "?";
cout << endl << "y/n: ";
cin >> yesOrNo;
}
cout << "Hooray! :)";
return 0;
}
int adjustGuess(int& random_number, int lowGuess, int highGuess)
{
random_number = rand() % (highGuess - lowGuess + 1) + lowGuess;
return (random_number);
}
int adjustMinMax(int random_number, int& highGuess, int& lowGuess, string lowOrHigh)
{
if (lowOrHigh == "l" || lowOrHigh == "low")
{
return(lowGuess = random_number);
}
if (lowOrHigh == "h" || lowOrHigh == "high")
{
return(highGuess = random_number);
}
}
答案 0 :(得分:0)
调整最小值和最大值必须在之前完成游戏进行新的猜测。 而不是:
adjustGuess(random_number, lowOrHigh, lowestGuess, highestGuess);
adjustMinMax(random_number, highestGuess, lowestGuess);
尝试:
adjustMinMax(random_number, highestGuess, lowestGuess);
adjustGuess(random_number, lowOrHigh, lowestGuess, highestGuess);
adjustMinMax还必须知道先前的猜测是太高还是太低,并且应该使用该信息来决定改变哪些。
另一个问题是你的adjustGuess功能似乎没有你认为它做的。对于先前的猜测是过高还是过低都应该是不确定的,并且当选择一个新的随机数时,它应该考虑最高的Guess和最低的Guess。尝试类似:
random_number = lowestGuess + rand() % (highestGuess - lowestGuess);
还有一些其他问题,例如yesOrNo必须是一个字符串,如果你希望它能够存储&#34; no&#34;。
如果你解决了这些问题,看看会发生什么。
答案 1 :(得分:0)
表达式yesOrNo == 'No'
正在将char
变量与不允许的字符串进行比较。此外,如果用户输入no,cin
对象将采用'n'并在输入缓冲区中保留'o'和'\ n'。然后下次你要求输入时,cin
将取'o'和'\ n'仍然在缓冲区中。您应该cin.ignore()
从缓冲区中删除额外的char
。