C++程序while循环结束后后续代码未执行无法运行问题求助
问题原因
你的代码存在两个核心错误导致循环后代码无法执行:
- 循环条件使用了赋值操作而非判断操作:
while (isTrue = true)是对isTrue变量赋值为true,表达式结果恒为true,相当于强制死循环。要做相等判断应该使用双等号==,可以直接简化为while(isTrue)。 - 循环退出分支中直接调用了
return语句:当用户输入-1触发结算逻辑时,你执行了return isTrue;,该语句会直接终止main函数,自然不会执行后续询问税率的代码,删掉该return语句即可。
修正后完整代码
#include <iostream> using namespace std; int main() { int priceArticle; int taxPercent; int total = 0; int totalAfterTax; int valueFinish = -1; bool isTrue = true; bool isTaxesTrue = true; while (isTrue) { cout << "How much money was the cost of your item? " << endl; cin >> priceArticle; if (priceArticle != valueFinish) { total += priceArticle; cout << total << endl; } if (priceArticle == valueFinish) { cout << "Your total before taxes is " << total << endl; isTrue = false; } } cout << "What's the percent of taxes you must pay?" << endl; cin >> taxPercent; // 后续税费计算逻辑可以在这里补充 return 0; }
内容的提问来源于stack exchange,提问作者Santiago Uribe Gil
相关产品推荐
相关产品推荐

