【问题标题】:Why does my function always return 1?为什么我的函数总是返回 1?
【发布时间】:2017-09-24 13:52:25
【问题描述】:

我正在编写一个函数,用于检查“noughts and crosss”或“三连胜”游戏中是否有赢家。

游戏首先在命令提示符下绘制 3 x 3 方格。然后用户在方块之间移动光标,并按下回车键放置一个“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;
}

【问题讨论】:

  • 您是否尝试过逐步运行函数,通过调试器,甚至只用笔和纸?
  • 在调试时,如果没有 X 或 O,请检查每个框中的内容。
  • 您不能索引 3 x 3 矩阵中的第 4 行或第 4 列。
  • for (i = 0; i &lt;= 3; i++) 在数组大小仅为[3][3] 时是错误的。
  • c0 基本数组,而不是 1 基本数组。该数组从[0][0][2][2],而不是从[1][1][3][3]

标签: c function for-loop if-statement return-value


【解决方案1】:

您正在传递一个 3x3 数组(每个维度中的索引为 0、1 和 2),但在您的循环中,您要迭代 4 次(索引 0、1、2 和 3)。在你的循环中尝试for (i = 0; i &lt; 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;
}

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 2019-06-26
    • 2013-01-09
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多