这个while循环导致我的程序挂起

时间:2019-10-22 13:05:34

标签: c++ loops data-structures while-loop

我有一个导致我的程序挂起的函数。我已经注释掉了该功能,其他所有功能都运行正常。程序到达循环应结束的位置,并且仅等待输入。 isBomb()函数只是一个获取器,它返回一个true / false值。该功能是扫雷游戏的一部分。我正在尝试找出一种方法来找出所选单元格附近有多少枚炸弹。我可以发布整个程序,但是大约250-350行。 makeNum方法是一个简单的getter,它将单元格号设置为等于参数的值。拒绝我投票之前,请让我知道是否有问题。我尝试搜索答案,但被卡住了。

void mazeDisplay::countBombAdj(int row, int col) {
    int counter = 0;
/*  for (int x = row - 1; x < row + 1; x++) {
        while ((x > - 1) && (x < 4)) {
            for (int y = col - 1; y < col + 1; y++) {
                while ((-1 < y) && (y < 4)) {
                    if (mazeCells[x][y].isBomb() == true)
                        counter += 1;
                }
            }
        }
    }*/

    mazeCells[row][col].makeNum(counter);
}

2 个答案:

答案 0 :(得分:5)

这是您的电话:

while ((x > - 1) && (x < 4))

x不变,该循环中没有任何break,因此循环是无限的。

类似地:

while ((-1 < y) && (y < 4)) 

就像其他人评论的那样,您循环if,而不是(无限)while循环:

void mazeDisplay::countBombAdj(int row, int col) {
    int counter = 0;
    for (int x = row - 1; x < row + 1; x++) {
        if ((x > - 1) && (x < 4)) {
            for (int y = col - 1; y < col + 1; y++) {
                if ((-1 < y) && (y < 4)) {
                    if (mazeCells[x][y].isBomb() == true)
                        counter += 1;
                }
            }
        }
    }

    mazeCells[row][col].makeNum(counter);
}

答案 1 :(得分:0)

一旦您进入了while循环之一,该条件就永远不会变为假,而您将永远陷入其中。

此外,改为使用if检查这些条件会使您仅扫描3 x 3的正方形,这是一个非常无聊的扫雷游戏。
您需要检查自己是否在木板内,而不是在那个小方块内。

我会遍历适当的范围,而不是跳过无效的单元格:

for (int x = std::max(0, row-1); x < std::min(number_of_rows, row+2); x++)
{
    for (int y = std::max(0, col-1); y < std::min(number_of_cols, col+2); y++)
    {
        if (mazeCells[x][y].isBomb())
            counter += 1;
    }
}