我试图编写一个程序,如果连续有多个X或O,则会调用函数win。我对向上倾斜的对角线胜利有困难。我可以提供任何关于我应该改变的建议吗?提前致谢。它调用无限循环而不是返回true。
bool left_diag_win(char **board, int num_rows, int num_cols) {
int i;
if (board[0][0] == '*') {
return false;
}
for (i = 1; i < num_rows; ++i) {
if (board[i][i] != board[0][0]) {
return false;
}
}
return true;
}
bool right_diag_win(char **board, int num_rows, int num_cols) {
int i;
if (board[0][num_cols - 1] == '*') {
return false;
}
for (i = 1; i < num_rows; ++i) {
if (board[i][num_cols - i - 1] != board[0][num_cols - 1]) {
return false;
}
}
return true;
}
答案 0 :(得分:0)
您的代码似乎正确,但您可能在其他地方遇到问题。这是一个表现如预期的例子:
#include <stdbool.h>
#include <stdio.h>
bool left_diag_win(char **board, int num_rows, int num_cols) {
if (board[0][0] == '*') {
return false;
}
for (int i = 1; i < num_rows; ++i) {
if (board[i][i] != board[0][0]) {
return false;
}
}
return true;
}
bool right_diag_win(char **board, int num_rows, int num_cols) {
if (board[0][num_cols - 1] == '*') {
return false;
}
for (int i = 1; i < num_rows; ++i) {
if (board[i][num_cols - i - 1] != board[0][num_cols - 1]) {
return false;
}
}
return true;
}
int main(void) {
char *matrix1[] = { "X****", "*X***", "**X**", "***X*", "****X" };
char *matrix2[] = { "****X", "***X*", "**X**", "*X***", "X****" };
printf("matrix:\n");
for (int i = 0; i < 5; i++) {
printf("%s\n", matrix1[i]);
}
printf("left-diagonal: %d\n", left_diag_win(matrix1, 5, 5));
printf("right-diagonal: %d\n\n", right_diag_win(matrix1, 5, 5));
printf("matrix:\n");
for (int i = 0; i < 5; i++) {
printf("%s\n", matrix2[i]);
}
printf("left-diagonal: %d\n", left_diag_win(matrix2, 5, 5));
printf("right-diagonal: %d\n\n", right_diag_win(matrix2, 5, 5));
return 0;
}
输出:
matrix:
X****
*X***
**X**
***X*
****X
left-diagonal: 1
right-diagonal: 0
matrix:
****X
***X*
**X**
*X***
X****
left-diagonal: 0
right-diagonal: 1