switch缺少break出现bug
bug代码
void input() {cin >> direction;switch (direction) {case 'w':newpr--;//行--break;case 's':newpr++;//行++break;/*bug代码 *///case 'a':// newpc--;//列--/*解决bug */case 'a':newpc--;break;case 'd':newpc++;//列++break;case 'q':cout << "你确定退出吗?(Y/N)" << endl;cin >> direction;//合理利用if (direction == 'Y') {gameOver = true;}break;}
}
bug原因分析:
在 input()
函数的 switch
语句中,case 'a'
分支缺少 break
语句,导致逻辑错误:
case 'a':newpc--;//列--
case 'd':newpc++;//列--break;
当输入 'a'
时,程序会先执行 newpc--
(向左移动),但由于没有 break
,会继续执行下一个 case 'd'
的 newpc++
(向右移动)。两次操作相互抵消,导致 newpc
最终没有变化,表现为无法向左移动。
而输入 'd'
时,虽然能正常执行 newpc++
,但用户可能因 'a'
无效而误以为 'd'
也有问题(实际 'd'
逻辑本身可行,但受 'a'
影响整体左右移动异常)。
Bug 解决方案
在 case 'a'
分支末尾添加 break
语句,确保每个分支逻辑独立执行: