C 1-100 猜谜游戏,其中计算机是一个猜谜

新手上路,请多包涵

我正在使用 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 许可协议

阅读 384
1 个回答

您选择 while((high-low)!=1) 作为您的 while 表达式的想法是什么?

您的代码基本上是在说-当 highlow 之间的差异为 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 )。

所以我认为你有两个问题。

  1. when you find yourself reducing guess by 0 then the player’s thought of number has to be low and you should set guess to be low 允许将此作为计算机的猜测呈现给用户。

并且 2) 当 highlow 之间的差异为 1 时,您需要找到一种允许输入 while 循环的方法。这允许 guess 的可能性 --- 当它等于 low 时呈现给玩家。

有人发帖

while(high > low)

我认为这很好。

但是您还需要检查 highlow 之间的差异何时为 1,因为 a) 您不想无休止地减少 guess b)此时数字的想法 必须low

所以:

 while((high>low){
    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;
        if( high-low == 1)
        {
          guess = low;
        }
        else
        {
          guess -= ( high - low ) / 2;
        }
    }

原文由 patchwork 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题