C++ 购物结算代码示例:计算不同商品总价
C++ 购物结算代码示例:计算不同商品总价
本代码使用 C++ 实现了一个简单的购物结算程序,可以计算不同商品的总价。用户可以输入购买的商品名称和数量,程序会自动计算总价。代码示例中包含价格表、购物车和总价计算功能。
#include <iostream>
#include <map>
using namespace std;
// 商品价格表
map<string, double> priceList = {
{'苹果', 3.5},
{'香蕉', 2.0},
{'橙子', 4.0},
{'葡萄', 5.5}
};
// 计算商品总价
double calculateTotalPrice(map<string, int> shoppingCart) {
double totalPrice = 0.0;
for (auto item : shoppingCart) {
string itemName = item.first;
int quantity = item.second;
// 检查商品是否在价格表中
if (priceList.find(itemName) != priceList.end()) {
double price = priceList[itemName];
double itemTotalPrice = price * quantity;
totalPrice += itemTotalPrice;
}
}
return totalPrice;
}
int main() {
map<string, int> shoppingCart;
// 输入购买的商品和数量
while (true) {
string itemName;
int quantity;
cout << "请输入要购买的商品名称(输入0结束):";
cin >> itemName;
// 输入0结束购物
if (itemName == "0") {
break;
}
cout << "请输入购买的数量:";
cin >> quantity;
// 将商品及数量添加到购物车
shoppingCart[itemName] += quantity;
}
// 计算总价
double totalPrice = calculateTotalPrice(shoppingCart);
// 输出总价
cout << "购物车中的商品总价为:" << totalPrice << "元" << endl;
return 0;
}
使用方法:
- 运行程序后,会要求你逐个输入购买的商品名称和数量。当你想结束购物时,输入商品名称为'0'即可。
- 输入购买的商品名称和数量后,程序会将商品及数量添加到购物车。
- 当你输入完所有的购买商品后,程序会计算购物车中商品的总价,并输出结果。
希望这段代码对你有帮助!如果有任何疑问,请随时提问。
原文地址: https://www.cveoy.top/t/topic/jWN 著作权归作者所有。请勿转载和采集!