C:矩阵元素的布尔测试

时间:2014-12-24 11:23:17

标签: c matrix boolean

为了更好地理解多维数组,我正在编写一个tic-tac-toe程序,意思是一个3x3数组,所有元素都初始化为-1。

当一行/列/对角线的所有元素相等(并且不为空,因此与-1不同)时,我试图使“获胜”条件成为真。

但是我一直在赢......当我不应该,并且当比赛结束时比赛继续进行。我该如何解决?

这是我的代码的一部分:

#define GRID_SIZE 3
#define EMPTY -1
#define PLAYER0 0
#define PLAYER1 1

printf("Player %d turn: Insert the tile coordinates\n", player);
scanf("%d %d", &x, &y);

/* Update tile */

if (player == PLAYER0)
    grid[x][y] = PLAYER0;
else
    grid[x][y] = PLAYER1;

/*  Winning diagonals? */

i = 0;
d1 = ((grid[i][i] == grid[i+1][i+1] == grid[i+2][i+2]) && (grid[i][i] != EMPTY));
d2 = ((grid[i][GRID_SIZE-i-1] == grid[i+1][GRID_SIZE-i] == grid[i+2][GRID_SIZE-i+1])     && (grid[i][GRID_SIZE-i-1] != EMPTY));

if ((d1) || (d2)) {
        printf("Player %d wins!\n", player);
        victory_or_draw = 1;
}

/*  Winning rows or column? */

for (j = 0; j < GRID_SIZE; ++j) {
    row = ((grid[i][j] == grid[i+1][j] == grid[i+2][j]) && (grid[i][j] != EMPTY));
    column = ((grid[j][i] == grid[j][i+1] == grid[j][i+2]) && (grid[j][i] != EMPTY)); 
    if ((row) || (column)) {
        printf("Player %d wins!\n", player);
        victory_or_draw = 1;
    }
}

2 个答案:

答案 0 :(得分:1)

比较运算符在C中不可传递,您应该使用布尔“和”运算符&&来组合不同的测试。

此外,在此处发布代码时,请将其简化为最小的示例。你的问题与矩阵元素的完成无关。

答案 1 :(得分:1)

你不能像这样比较

(grid[i][i] == grid[i+1][i+1] == grid[i+2][i+2])

使用

(grid[i][i] == grid[i+1][i+1] && grid[i][i] == grid[i+2][i+2])

将d1和d2更改为

d1 = ((grid[i][i] == grid[i+1][i+1] && grid[i][i] == grid[i+2][i+2]) && (grid[i][i] != EMPTY));
d2 = ((grid[i][GRID_SIZE-i-1] == grid[i+1][GRID_SIZE-i] && grid[i][GRID_SIZE-i-1] == grid[i+2][GRID_SIZE-i+1]) && (grid[i][GRID_SIZE-i-1] != EMPTY));

同样改变for循环中的内容。