C++ 仓库结算代码示例:库存管理与价格计算

以下是一个用 C++ 编写的仓库结算的代码示例,展示如何使用 map 数据结构管理商品价格、库存和购物车,并进行库存检查、价格计算和总价输出。

#include <iostream>
#include <map>
using namespace std;

// 商品价格表
map<string, double> priceList = {
    {'苹果', 3.5},
    {'香蕉', 2.0},
    {'橙子', 4.0},
    {'葡萄', 5.5}
};

// 仓库库存表
map<string, int> inventory = {
    {'苹果', 10},
    {'香蕉', 5},
    {'橙子', 8},
    {'葡萄', 12}
};

// 计算商品总价
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() && inventory.find(itemName) != inventory.end()) {
            int availableQuantity = inventory[itemName];
            
            // 检查库存是否足够
            if (quantity <= availableQuantity) {
                double price = priceList[itemName];
                double itemTotalPrice = price * quantity;
                totalPrice += itemTotalPrice;
                
                // 更新库存
                inventory[itemName] -= quantity;
            } else {
                cout << "库存不足,无法购买更多的" << itemName << "!" << endl;
            }
        }
    }
    
    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;
}

使用方法:

  1. 运行程序后,会要求你逐个输入购买的商品名称和数量。当你想结束购物时,输入商品名称为'0'即可。
  2. 输入购买的商品名称和数量后,程序会将商品及数量添加到购物车。
  3. 程序会检查购买的商品是否在价格表和库存表中,并检查库存是否足够。
  4. 如果库存足够,程序会计算总价并输出。
  5. 如果库存不足,程序会显示相应的提示信息。

代码说明:

  • 使用 map 数据结构存储商品价格、库存和购物车信息,方便查找和更新。
  • 函数 calculateTotalPrice() 用于计算购物车中所有商品的总价,并进行库存检查和更新。
  • 主函数 main() 负责接收用户输入的商品名称和数量,并调用 calculateTotalPrice() 函数计算总价并输出。

扩展应用:

  • 可以添加用户身份验证功能,记录用户的购买历史和消费记录。
  • 可以添加折扣功能,根据商品类型或购买数量进行折扣计算。
  • 可以添加打印发票功能,生成包含商品名称、数量、价格和总价的发票。

希望这段代码对你有帮助!如果有任何疑问,请随时提问。

C++ 仓库结算代码示例:库存管理与价格计算

原文地址: https://www.cveoy.top/t/topic/jW8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录