Jak*_*und 0 c for-loop if-statement function return-value
我正在编写一个函数,用于检查"noughts and crosses"游戏中是否有赢家,或者"连续三次".
游戏的工作原理是首先在命令提示符中绘制3 x 3个方块.然后用户在方块之间移动光标,然后按Enter键以放置"X".下一个选定的方格中放置一个"O",然后再放一个"X",依此类推.在第5轮(第一个可能的转弯可能有胜利者)之后,该程序检查在每个回合之后是否有赢家,如果在9转之后没有找到(当所有方块都有某些东西时)该程序宣布平局.
但是,我为检查获胜者而编写的函数在被调用时总是返回1,这意味着有一个胜利者(更具体地说是X,因为那是最后一次移动的那个).因此,无论方块包含什么,游戏都在第5轮结束.
这是我的代码:
int control(char p[3][3]) {
int i;
for (i = 0; i <= 3; i++) //Checks if any of the horizontals have 3 of the same markers in a row
if (p[i][1] == p[i][2] && p[i][2] == p[i][3])
return 1;
for (i = 0; i <= 3; i++) //Checks if any of the vertical columns have 3 of the same markers
if (p[1][i] == p[2][i] && p[2][i] == p[3][i])
return 1;
else if (p[1][1] == p[2][2] && p[2][2] == p[3][3]) //Checks if top left, middle and bottom right squares have the same marker
return 1;
else if (p[3][1] == p[2][2] && p[2][2] == p[1][3]) //Checks if the top right, middle and bottom left have the same marker
return 1;
else //If none of the above have the same 3 markers, the game keeps going
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您传入的是3x3数组(每个维度中的索引为0,1和2),但在循环中,您将迭代4次(索引0,1,2和3).请尝试for (i = 0; i < 3; i++)在循环中,因为您的循环现在将检查超出p数组边界的值,如果您运气不好,则该内存的内容会导致控制函数返回1.
最后,我认为最后的else块不应该在循环中,而是在它之外:如果两个循环都已经运行而你还没有返回,你可以安全地返回0,但你不想返回0在检查所有垂直行程之前过早.
这是函数,索引和对角线检查的变化以及第二个for循环中的最终else块被捕获:
int control(char p[3][3]) {
int i;
/* Check horizontals */
for (i = 0; i < 3; i++)
if (p[i][0] == p[i][1] && p[i][1] == p[i][2])
return 1;
/* Check verticals */
for (i = 0; i < 3; i++)
if (p[0][i] == p[1][i] && p[1][i] == p[2][i])
return 1;
/* Check diagonals */
if (p[0][0] == p[1][1] && p[1][1] == p[2][2])
return 1;
if (p[2][0] == p[1][1] && p[1][1] == p[0][2])
return 1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)