首页 > 解决方案 > 为什么我的 for 循环不能找到正确的错误?

问题描述

我有一个网格,并且有一个名为 Move(int s) 的成员函数,它应该将移动器图标移动到它当前面向的任何方向,即 's' 的空间量。如果在要移动到的移动器前面的任何位置有一个块字符('#'),则该函数应该失败并将光标留在正确的位置。似乎 bool 语句总是等同于 true,但我似乎无法在我的代码中找到位置。

在我的示例输出中,移动功能永远不会失败,移动器似乎总是穿过墙壁或更换墙壁。

我不会发布所有 4 个方向,但我会发布北方和西方:

bool Grid::Move(int s) {
bool canMove = true;  //initialize the bool variable
if (direction == NORTH) {
    if ((mRow - s) >= 0) {
        for (int i = mRow; i >= (mRow - s); i--) {
            if (matrix[i][mCol] == '#') {
                canMove = false;
            } else if (matrix[i][mCol] != '#') {
                canMove = true;
            }
        }
        if (canMove == true) {
            matrix[mRow][mCol] = '.';
            mRow = (mRow - s);
            matrix[mRow][mCol] = '^';
            return true;
        }else{
            matrix[mRow][mCol] = '^';
        }
    } else
        return false;
} else if (direction == WEST) {
    if ((mCol - s) >= 0) {
        for (int i = mCol; i >= (mCol - s); i--){
            if (matrix[mRow][i] == '#'){
                canMove = false;
            } else if (matrix[mRow][i] != '#')
                canMove = true;
        }
        if (canMove == true) {
            matrix[mRow][mCol] = '.';
            mCol = (mCol - s);
            matrix[mRow][mCol] = '<';
            return true;
        }else
            matrix[mRow][mCol] = '<';
    }else
        return false;
} 

标签: c++arrays2d

解决方案


您正在设置canMove循环的每次迭代。它最后一次获得的价值就是它将拥有的价值。

由于目标是查看移动是否在整个持续时间内有效,因此您无需设置canMove为,true因为一旦它变为错误,它应该保持这种状态。(当发生这种情况时,您可以break退出循环。)


推荐阅读