如何用循环替代C++披萨店程序中的多个if语句?
问题
我正在初学者编程课程中编写一个披萨店场景的C++基础程序,需求如下:
- 根据预算询问用户是否需要额外披萨配料
- 若用户选择是,则更新预算(Budget)和账单(Invoice)
- 展示所选披萨配料的汇总
- 展示最终账单和剩余金额
目前我用多个if语句输出所选配料:
cout << "\nHere is a summary of your order: \n" ; if (Olives2 == true){ cout << "-Olives\n"; } if (Onions2 == true){ cout << "-Onions\n"; } if (Cheese2 == true){ cout << "-Cheese\n" ; } if (Salami2 == true){ cout << "-Salami\n"; } if (Shrimps2 == true){ cout << "-Shrimps\n\n"; }
这些布尔变量(如Cheese2)通过switch语句更新,示例如下:
if (Budget >= Shrimps1 ) { cout << "Any Shrimp? y/n "; cin >> Toppings; switch (Toppings) { case 'y': Invoice = Invoice + Shrimps1; Budget = 100 - Invoice; cout << "Your subtotal is R" << Invoice << ", with a remainder of R" << Budget << endl; Shrimps2 = true; break; case 'n': cout << "Your subtotal is R" << Invoice << ", with a remainder of R" << Budget << endl; break; } }
请问是否可以用循环替代这些if语句,让代码更简洁?
解决方案
当然可以用循环替代重复的if语句,核心是把配料的名称、价格、选中状态打包成统一的数据结构,用容器存储后遍历处理,既能精简代码,还能大幅提升扩展性。
1. 定义配料数据结构
用结构体把配料的相关信息绑定在一起,替代原来零散的独立变量:
#include <iostream> #include <vector> using namespace std; struct Topping { string name; // 配料名称 int price; // 配料价格 bool selected; // 是否被选中 };
2. 初始化配料列表
把所有配料信息存入vector,后续新增配料只需在列表里添加一行即可:
int main() { int budget = 100; int invoice = 0; vector<Topping> toppings = { {"Olives", 10, false}, {"Onions", 8, false}, {"Cheese", 12, false}, {"Salami", 15, false}, {"Shrimps", 20, false} };
3. 用循环替代重复的switch逻辑
遍历配料列表,逐个询问用户需求,同时更新预算和选中状态:
char choice; for (auto &topping : toppings) { if (budget >= topping.price) { cout << "Any " << topping.name << "? y/n "; cin >> choice; if (choice == 'y') { invoice += topping.price; budget -= topping.price; topping.selected = true; } cout << "Your subtotal is R" << invoice << ", with a remainder of R" << budget << endl; } else { cout << "Not enough budget for " << topping.name << endl; } }
4. 用循环替代多个if输出汇总
遍历配料列表,只打印用户选中的配料:
cout << "\nHere is a summary of your order: \n"; for (const auto &topping : toppings) { if (topping.selected) { cout << "-" << topping.name << "\n"; } } cout << "\nFinal Invoice: R" << invoice << "\nRemaining Budget: R" << budget << endl; return 0; }
优化后的优势
- 扩展性强:新增配料不用修改逻辑代码,只需在配料列表里添加一行数据
- 代码简洁:消除了大量重复的if和switch语句,可读性和维护性大幅提升
- 逻辑更严谨:直接用
budget -= topping.price更新预算,避免原代码中固定100的硬编码问题
内容的提问来源于stack exchange,提问作者Corne
相关产品推荐
相关产品推荐

