c++ - 为什么我的 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;
}
解决方案
您正在设置canMove
循环的每次迭代。它最后一次获得的价值就是它将拥有的价值。
由于目标是查看移动是否在整个持续时间内有效,因此您无需设置canMove
为,true
因为一旦它变为错误,它应该保持这种状态。(当发生这种情况时,您可以break
退出循环。)
推荐阅读
- python - Python 3.7 密钥错误
- scala - 捕捉scala中过滤掉的内容的最佳方法是什么?
- javascript - 使用本机 javascript 从服务器获取文本或 json 无法正常工作
- node.js - 公司如何将管理员角色分配给用户?
- spring-boot - 反应式编程:Spring WebFlux:如何构建微服务调用链?
- java - 在 java 8 中使用 Files.newDirectoryStream() 时如何关闭文件处理程序
- swift - 如果我强制打开一个结构实例,Swift 会复制它吗?
- python - 如何在python的子进程中执行一组语句?
- karate - 将 ReportPortal 与空手道 0.9.4 集成
- java - 在 Spring Boot 中,自定义 JWE 过滤器阻止了 CORS 选项请求