[英]tic-tac-toe while and ||
hi im 17 and trying to teach myself c++. 嗨,我17岁,并试图教自己c ++。 For one of my first projects I am trying to write a tic-tac-toe game and play vs an AI.
对于我的第一个项目,我试图编写一个井字游戏并玩AI。 So the code im having trouble with is this
所以我遇到麻烦的代码是这个
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;
};
I get the message " do you want to be x or o?", but then I enter x or o and it keeps repeating the same question. 我收到消息“您想成为x或o吗?”,但随后输入x或o,它会不断重复同样的问题。 I think it has to do with the while loop.
我认为这与while循环有关。 Any help is appreciated.
任何帮助表示赞赏。
char player, computer;
while (player != 'x' || player != 'o' ) {
First of all, player
isn't initialized to anything, so it contains random garbage. 首先,
player
没有初始化为任何东西,因此它包含随机垃圾。 You shouldn't be reading from it. 您不应该阅读它。 At least initialize it to some known value.
至少将其初始化为某个已知值。
Second, your condition will always be true. 其次,您的情况将永远是正确的。 Suppose that
player
is 'x'
. 假设
player
是'x'
。 That satisfies the condition player != 'o'
. 满足条件
player != 'o'
。
You probably mean: 您可能是说:
while (player != 'x' && player != 'o') {
Your loop end condition is wrong, and you shouldn't check until you've asked once. 您的循环结束条件是错误的,只有在问完一次之后,您才应该检查。
do {
cout << "do you want to be x or o?";
cin >> player;
} while (player != 'x' && player != 'o');
Your problem is the conditional. 您的问题是有条件的。 What I think you mean is
while (player != 'x' && player != 'o')
, ie when player
is neither x nor o. 我认为您的意思是
while (player != 'x' && player != 'o')
,即player
既不是x也不是o。
while ( (player == 'x' || player == 'o') == false )
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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.