酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

description 汤汤开了一家咖啡店,在研发新品的时候,她发现不同品牌的牛奶味道不一样,拿铁的味道也会有微妙的区别,而且鲜牛奶的口感会比常温奶更好。经过精心的筛选,她最终选定了两家巴氏杀菌鲜牛奶供应商。每隔一段时间。小汤都会去市场购买当天最新鲜的牛奶,但由于供应商的库存和价格会有波动,每次进货的数量并不固定。 品牌a的鲜牛奶是塑料瓶包装,保质期只有7天;品牌b的鲜牛奶是专用纸盒包装,保质期有15天;为了减少浪费,汤汤会优先使用临近保质期的鲜牛奶,而过了保质期的牛奶,就只能处理掉了。 汤汤会记下每次进货的时间和数量以及每天的消耗量,以方便盘点库存。不用考虑每日消耗量超过剩余量的情况哦,汤汤会提前采购的~ input 第一行输入整数 n,表示有n条操作记录; 之后n行,每行是一个操作,操作格式如下: 1 purchas 10 20 // 开店第1天,购买了a品牌鲜奶10l,b品牌鲜奶20l 2 cost 10 // 开店第2天,消耗鲜奶10l 3 check // 开店第3天,盘点 output 第一行,输出a品牌牛奶的盘点结果,包括库存量,语言方向:C++

以下是用 C++ 实现的代码示例: ```cpp #include <iostream> #include <vector> struct Milk { int brand; int quantity; int expirationDay; }; class CoffeeShop { private: std::vector<Milk> stocks; void updateExpiration() { for (auto& milk : stocks) { if (milk.expirationDay > 0) { milk.expirationDay--; } } } void consume(int quantity) { int totalConsumed = 0; for (auto it = stocks.begin(); it!= stocks.end();) { if (it->expirationDay > 0 && totalConsumed < quantity) { if (it->quantity <= quantity - totalConsumed) { totalConsumed += it->quantity; it = stocks.erase(it); } else { it->quantity -= quantity - totalConsumed; totalConsumed = quantity; } } else { it++; } } } public: void purchase(int brandAQuantity, int brandBQuantity) { Milk brandA = {1, brandAQuantity, 7}; Milk brandB = {2, brandBQuantity, 15}; stocks.push_back(brandA); stocks.push_back(brandB); } void check() { int brandAStock = 0; for (const auto& milk : stocks) { if (milk.brand == 1) { brandAStock += milk.quantity; } } std::cout << "A 品牌牛奶的库存量: " << brandAStock << std::endl; } void handleOperations() { int n; std::cin >> n; for (int i = 0; i < n; i++) { int operation; std::cin >> operation; if (operation == 1) { int brandAQuantity, brandBQuantity; std::cin >> brandAQuantity >> brandBQuantity; purchase(brandAQuantity, brandBQuantity); } else if (operation == 2) { int consumption; std::cin >> consumption; consume(consumption); } else if (operation == 3) { check(); } updateExpiration(); } } }; int main() { CoffeeShop shop; shop.handleOperations(); return 0; } ``` 以下是 3 个改进建议: 1. 可以添加错误处理机制,比如输入不符合格式时的处理。 2. 可以将一些功能封装成单独的函数,以提高代码的可读性和可维护性。 3. 考虑使用更高效的数据结构来存储库存信息,例如优先队列。 [2024-12-29 17:06:34 | AI写代码神器 | 663点数解答]

相关提问