C++自动售货机开发:如何用for循环计算用户输入的累计金额?
问题分析与修正建议
首先你的代码存在几个关键问题需要修正:
while循环条件逻辑错误:
while (choice == 1 || 2 || 3)的写法不符合语法规范,正确的逻辑判断应该是while (choice == 1 || choice == 2 || choice == 3),否则数字2、3会被当作布尔值true,导致循环永远无法终止。for循环完全误用:你嵌套的for循环语法错误(
i = true是赋值操作而非判断),且这种场景根本不需要嵌套循环。作业要求使用for循环,其实可以用它来遍历所有饮料的购买数量与单价,累加计算总价,这才是符合要求的用法。
以下是修正后的完整代码,重点实现了for循环计算总价的逻辑:
#include <iostream> using namespace std; int main() { int choice = 0; int amount1 = 0, amount2 = 0, amount3 = 0; // 用数组存储饮料单价和对应购买数量,方便for循环遍历 float drinkPrices[] = {1.0, 0.5, 0.25}; int drinkAmounts[] = {amount1, amount2, amount3}; int drinkCount = sizeof(drinkPrices) / sizeof(drinkPrices[0]); // 改为当用户未选择"结算"时持续循环 while (choice != 4) { cout << "Available sodas and prices:" << endl; cout << "1. Coke - $1" << endl; cout << "2. Pepsi - $0.50" << endl; cout << "3. Root Beer - $0.25" << endl; cout << "4. Finish and calculate total" << endl; cout << "Please enter the number of the soda you would like to purchase: "; cin >> choice; if (choice == 1) { cout << "How many Cokes would you like?: "; cin >> amount1; cout << "The total amount for " << amount1 << " Cokes is: $" << amount1 * 1 << endl; } else if (choice == 2) { cout << "How many Pepsi would you like?: "; cin >> amount2; cout << "The total amount for " << amount2 << " Pepsi is: $" << amount2 * 0.5 << endl; } else if (choice == 3) { cout << "How many Root Beers would you like?: "; cin >> amount3; cout << "The total amount for " << amount3 << " Root Beers is: $" << amount3 * 0.25 << endl; } else if (choice == 4) { // 更新数组中的最新购买数量 drinkAmounts[0] = amount1; drinkAmounts[1] = amount2; drinkAmounts[2] = amount3; float total = 0.0; // 用for循环遍历所有饮料,累加计算总价 for (int i = 0; i < drinkCount; i++) { total += drinkAmounts[i] * drinkPrices[i]; } cout << "Your total cost today is: $" << total << ". Thank you for shopping at the Soda Shop!" << endl; return 0; } else { cout << "Invalid option. Please select a valid soda choice or choose 4 to finish." << endl; } cout << endl; } return 0; }
关于for循环的说明
这里用for循环的核心目的是批量处理所有饮料的总价计算:遍历每种饮料的购买数量和对应单价,将单种饮料的总价(数量×单价)累加到总金额中。这种写法不仅满足作业要求,还具备扩展性——如果后续新增饮料,只需在数组中添加对应的价格和数量变量,无需修改计算逻辑。
内容的提问来源于stack exchange,提问作者NazrimLoop
相关产品推荐
相关产品推荐

