【问题标题】:Why does my OR conditions to check string for matches always return true为什么我的 OR 条件检查字符串是否匹配总是返回 true
【发布时间】:2014-12-10 02:30:15
【问题描述】:

我正在编写经典的“猜我的号码”程序。

我似乎不明白为什么即使在我写了“成功”并转到默认路由之后,while 循环也没有停止工作。

int xRan;

void rdm(int to, int from){
    srand(time(NULL));
    xRan = rand()%to+from;
}

void iGuess(){
    string b;
    int tries = 1;

    cout <<  "Think of a number between 1 and 100" << endl;
    rdm(100, 1);

    while(b != "Success" || b != "success"){

        cout << "is your number higher or lower than  " << xRan << ". (attempt #" << tries << ")" <<  endl;
        cout << "If I guessed your number, please type 'Success' " << endl;
        cout << "-->";
        cin >> b;

        if(b == "Lower" || b == "lower"){
            rdm(xRan, 1);
            tries++;

        }else if(b == "Higher" || b == "higher"){
            rdm(100, xRan);
            tries++;

        }else{

        cout << "This is not a valid choice." << endl;

        }

    }
    cout << "I'm so good! I did it in " << tries << "attempts!" << endl;
}

【问题讨论】:

  • Zeptile,我已经删除了第二个问题“第二个,我想要一些关于编写更好的 AI 来查找号码的建议。”从您的帖子中获取,因为通常将 2 个问题合二为一并不是一个好主意。随时恢复我的更改并自己改进您的问题。您可以将第二个问题作为新问题提出,但请确保搜索类似的帖子,因为您可能不是唯一一个编写此类游戏的人。

标签: c++ while-loop artificial-intelligence


【解决方案1】:

您永远不会离开您的 for 循环,因为您正在检查它是“成功”还是“成功”。任何一个都可以是真的并进入循环。因此,无论您是否使用大写字母键入它,其中之一都是正确的。而是写

while(b != "Success" && b != "success")

【讨论】:

  • 虽然这个建议解决了直接的问题并因此得到了正确的答案,但请不要在你的代码中使用它来进行不区分大小写的比较,而是遵循stackoverflow.com/questions/11635/…中的建议
猜你喜欢
  • 2010-10-17
  • 1970-01-01
  • 2015-02-20
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-17
相关资源
最近更新 更多