2012-02-21 107 views
1

嗨IM 17,并试图教自己C++。对于我的第一个项目,我正在尝试写一个tic-tac-toe游戏,并与AI进行比赛。所以遇到问题的代码IM是这个tic-tac-toe while and ||

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循环有关。任何帮助表示赞赏。

+0

这是一个例如,从书中的文字? – 2012-02-21 05:12:42

+0

警告,您在初始化之前检查玩家! 在用户被问到之前,玩家可能会随机以'x'或'o'结尾!在使用它们之前,您必须初始化变量。 – abelenky 2012-02-21 05:13:00

+0

CodingMastero这不是,它只是我想出了 – 2012-02-21 05:18:11

回答

6

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

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

好的谢谢,我正在考虑做一个虽然,但不知道 – 2012-02-21 05:10:44

7
char player, computer; 

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

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

二,你的病情永远是真的。假设player'x'。满足条件player != 'o'

你大概的意思是:

while (player != 'x' && player != 'o') { 
+0

啊谢谢,现在澄清它,但我应该初始化玩家,我该怎么做? – 2012-02-21 05:09:55

+0

对于你的情况,你可以初始化它不是''x''和''o''(例如:'char player ='a';')。但是使用像StilesCrisis这样的'do-while'循环会更好,所以你只有在写完之后才检查'player'的值。 – jamesdlin 2012-02-21 05:13:26

1

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

+0

和初始化球员 – 2012-02-21 05:16:59

0
while ((player == 'x' || player == 'o') == false) 
+0

'==假'?好恶。这就是'!'操作符的用途。 – jamesdlin 2012-02-21 05:15:59

+1

为什么你需要在布尔表达式中使用== false – 2012-02-21 05:16:10

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; 
    };