首页 > 解决方案 > C++ if 语句在只满足一个条件时仍然为真

问题描述

我正在用 C++ 创建一个井字游戏程序并且几乎完成了它,我遇到的问题是当游戏需要以平局结束时。我创建了一个if-statement来检查何时选择了特定的组合,即使只满足一个条件,它也会发现它是正确的。

这是代码...

//takes the users selections and sees if all spots are filled in without a match.
if((b1== "O" || "X") && (b2 == "O" || "X") && (b3 == "O" || "X")){
        cout << "The game ended in a tie.";
      // Flip = 3 ends the game in a tie.
        flip = 3;
    }


例如...当我将 `b1` 更改为 `"O"` 或 `"X"` 时,游戏以平局结束,即使 `b2` 和 `b3` 仍然是空的。

标签: c++if-statementoperatorstic-tac-toetie

解决方案


条件:

b1== "O" || "X"

评估为:

(b1=="O") || "X"

这总是正确的。你可能想要:

(b1=="O" || b1=="X")

推荐阅读