我正在使用 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;
}
原文由 Placid 发布,翻译遵循 CC BY-SA 4.0 许可协议
您选择
while((high-low)!=1)
作为您的 while 表达式的想法是什么?您的代码基本上是在说-当
high
和low
之间的差异为 1 时,正确的数字必须是high
。这就是为什么当有人选择最低值(在本例中为 1 )时它不起作用的原因。您需要确保将最低值
low
guess
给用户。所以 - 单步执行您的代码:
让我们以
MIN_VALUE
为 1 为例,玩家选择 1 作为他们的数字。现在,当high
为 3 且guess
为 2 时,您将进入 while 循环,因为当被问及他们选择的数字是否小于或等于guess
时,玩家会回答“Y”---
,high
最终为 2。有趣的
guess
保持在 2 因为它减少了(high-low)/2
。向下舍入为 0。这意味着guess
永远不会达到最低值 - 这是一个问题。继续 - 下次评估 while 表达式时,它返回 false (因为 2-1 == 1 )。
然后你返回
high
(目前是 2 )。所以我认为你有两个问题。
guess
by 0 then the player’s thought of number has to below
and you should setguess
to below
允许将此作为计算机的猜测呈现给用户。并且 2) 当
high
和low
之间的差异为 1 时,您需要找到一种允许输入 while 循环的方法。这允许guess
的可能性---
当它等于low
时呈现给玩家。有人发帖
我认为这很好。
但是您还需要检查
high
和low
之间的差异何时为 1,因为 a) 您不想无休止地减少guess
b)此时数字的想法 必须 是low
。所以: