首页 > 解决方案 > 这个while循环导致我的程序挂起

问题描述

我有一个导致我的程序挂起的功能。我已经注释掉了这个功能,其他一切都运行得很好。程序到达循环应该结束的地方,它只是等待输入。isBomb() 函数只是一个 getter 并返回一个真/假值。该功能是扫雷游戏的一部分。我正在尝试找出一种方法来确定与所选单元格相邻的炸弹数量。我可以发布整个程序,但它大约是 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);
}

标签: c++loopsdata-structureswhile-loop

解决方案


这是你的行:

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);
}

推荐阅读