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

Joh*_*ell 0 c++ loops while-loop data-structures

我有一个导致程序挂起的函数。我已经注释掉了该功能,其他所有功能都运行正常。程序到达循环应结束的位置,并且仅等待输入。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);
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*ans 5

这是你的台词:

while ((x > - 1) && (x < 4))
Run Code Online (Sandbox Code Playgroud)

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

同样适用于:

while ((-1 < y) && (y < 4)) 
Run Code Online (Sandbox Code Playgroud)

就像其他人评论的那样,您看起来是什么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);
}
Run Code Online (Sandbox Code Playgroud)