用c++写一个汉堡购物
时间: 2024-09-21 13:09:13 浏览: 39
在C++中编写一个简单的汉堡购物程序,可以模拟顾客选择各种配料来定制汉堡的过程。这里我们创建一个基础的命令行界面示例:
```cpp
#include <iostream>
#include <string>
// 定义汉堡及其配料
enum class BurgerPart {
BUN,
PATTY,
CHEESE,
LETTUCE,
TOMATO,
ONION,
PICKLE
};
// 汉堡类,存储价格和基本信息
class Burger {
public:
double getPrice(BurgerPart part) {
switch (part) {
case BurgerPart::BUN: return 1.0;
case BurgerPart::PATTY: return 2.5;
case BurgerPart::CHEESE: return 0.5;
// ...其他配料的价格...
default: return 0.0; // 默认值
}
}
void addPart(BurgerPart part) {
prices[static_cast<int>(part)] += 1;
}
private:
std::vector<double> prices; // 存储每个配料的价格
};
int main() {
Burger burger;
BurgerPart choice;
std::cout << "Welcome to the Burger Shop!\n";
while (true) {
std::cout << "Choose a part (BUN, PATTY, CHEESE, etc.) or type 'quit' to exit: ";
std::cin >> choice;
if (choice == BurgerPart::QUIT) break;
std::cout << "You've chosen " << static_cast<char>(choice) << ".\n";
burger.addPart(choice);
std::cout << "The total cost so far is $" << burger.getPrice(choice) << ".\n";
}
std::cout << "Your final bill is $" << calculateTotalCost(burger.prices) << ".\n";
return 0;
}
double calculateTotalCost(const std::vector<double>& prices) {
double total = 0;
for (auto price : prices) {
total += price;
}
return total;
}
```
在这个例子中,用户可以选择汉堡的各个部分,并实时看到总费用。当输入"quit"时,程序结束。`calculateTotalCost`函数用于计算所有配料的总价。
阅读全文