为什么我的for循环没有收到正确的错误?

问题描述 投票:-2回答:1

我有一个网格,并有一个名为Move(int 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++ arrays 2d
1个回答
1
投票

你在循环的每次迭代中设置canMove。无论它在最后一次获得的价值是它将具有的价值。

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

© www.soinside.com 2019 - 2024. All rights reserved.