【发布时间】:2015-07-23 00:02:55
【问题描述】:
我只是 C++ 的初学者,在编写创建井字游戏的代码时,我遇到了 while 语句,该语句将推动游戏继续运行,直到满足获胜条件:
while(((table[0][0]!='X')&&(table[1][1]!='X')&&(table[2][2]!='X')))
这只是对角线条件(把所有条件都放在你眼里……)。 问题是即使条件得到满足,这也不起作用(我确定因为我最后使用了 cout),但是当我用 || 更改 && 时条件工作! 我想可能是因为 != 影响了一切??
编辑:最小示例(我删除了浮点数!):
#include <iostream>
using namespace std;
int main()
{
int tailleX(3),tailleY(3); //The Size of the table.
char table[tailleX][tailleY]; //TictacToe table.
table[0][0]='N';
table[0][1]='N';
table[0][2]='N';
table[1][0]='N';
table[1][1]='N'; //Randomly filling the array to avoid an error
table[1][2]='N';
table[2][0]='N';
table[2][1]='N';
table[2][2]='N';
int coorP1; //The Coordinate of the square (Exp: x=1 , y=2 will be 1.2)
while(((table[0][0]!='X')&&(table[1][1]!='X')&&(table[2][2]!='X'))) //For the minimal example I made just the diagonal condition
{
cout<<"PLAYER1: Enter the coordination to score: (Exemple: 1, 2, 3..) "<<endl;
cin>>coorP1;
switch(coorP1) //Filling the square depending on the coordinates.//I used If because Switch does not work.
{
case 1:
table[0][0]='X';
break;
case 2:
table[0][1]='X';
break;
case 3:
table[0][2]='X';
break;
case 4:
table[1][0]='X';
break;
case 5:
table[1][1]='X';
break;
case 6:
table[1][2]='X';
break;
case 7:
table[2][0]='X';
break;
case 8:
table[2][1]='X';
break;
case 9:
table[2][2]='X';
break;
}
}
cout<<"You won"<<endl;
return 0;
}
【问题讨论】:
-
欢迎来到 Stack Overflow!请将您的问题editminimal reproducible example 或SSCCE (Short, Self Contained, Correct Example)
-
准确比较浮点数和
==非常棘手。这是因为许多数字不能用浮点位完美表示。如果你觉得特别有勇气,你应该阅读What Every Computer Scientist Should Know about Floating Point Arithmetic -
您是否尝试过在 while 条件上设置断点并使用调试器单步执行它,检查
table的值? -
虽然@Collin 的链接很有用(如果您想了解所有血淋淋的细节,您应该阅读该链接),here's an easier-to-understand alternative。
-
首先,您在这里调用了未定义的行为。当你在 C++ 中声明一个数组时,你给它的值是大小,而不是最大索引。所以如果你说
int array[2],这意味着数组大小为2,你只能访问array[0]和array[1]。如果要访问array[2],则需要使array更大(即改为将其声明为int array[3])。
标签: c++ while-loop inequality