1

嗨,我 17 岁,正在尝试自学 C++。对于我的第一个项目之一,我正在尝试编写井字游戏并与 AI 对战。所以我遇到问题的代码是这样的

main() {

    char player, computer;

    while (player != 'x' || player != 'o' )
    {
        cout << "do you want to be x or o?";
        cin >> player;
    };

    if (player == 'x' ) computer == 'o';
    else computer == 'x';

    cout << "player is: " << player << endl <<  "computer is: " << computer ;
    cout << computer;
};

我收到消息“你想成为 x 还是 o?”,但随后我输入 x 或 o,它不断重复相同的问题。我认为这与while循环有关。任何帮助表示赞赏。

4

5 回答 5

7
char player, computer;

while (player != 'x' || player != 'o' ) {

首先,player没有初始化任何东西,所以它包含随机垃圾。你不应该从中阅读。至少将其初始化为某个已知值。

其次,你的条件永远是真实的。假设player'x'。那满足条件player != 'o'

你可能的意思是:

while (player != 'x' && player != 'o') {
于 2012-02-21T05:08:42.743 回答
5

你的循环结束条件是错误的,你不应该检查,直到你问过一次。

do {
    cout << "do you want to be x or o?";
    cin >> player;
} while (player != 'x' && player != 'o');
于 2012-02-21T05:08:57.390 回答
1

你的问题是有条件的。我认为您的意思是while (player != 'x' && player != 'o'),即何时player既不是 x 也不是 o。

于 2012-02-21T05:09:01.457 回答
0
while ( (player == 'x' || player == 'o') == false )
于 2012-02-21T05:09:19.370 回答
0
    char player = ' '; // always init variables
    while (player != 'x' && player != 'o' ) //exit if false, when player == x or == o
    {
        cout << "do you want to be x or o?";
        cin >> player;
    };
于 2012-02-21T05:15:31.617 回答