酷代码 AI
菜单
服务商

乌拉乎的书桌上摆满了零食,已知零食共分成10个不同的种类,种类编号分别为数字1~10,而乌拉乎为了能更有规律的吃零食,想要知道每种零食分别有几包。现在请你帮乌拉乎设计一个程序,完成对每种零食数量的统计。C++(简写)

```cpp #include <iostream> #include <map> using namespace std; int main() { map<int, int> snackCount; // 使用map存储种类编号和对应数量 int snackType; cout << "请输入零食种类编号(1~10),输入0结束:" << endl; while (cin >> snackType && snackType != 0) { if (snackType >= 1 && snackType <= 10) { snackCount[snackType]++; // 对应种类数量加1 } else { cout << "编号无效,请输入1~10的数字。" << endl; } } cout << "统计结果:" << endl; for (int i = 1; i <= 10; i++) { cout << "种类" << i << ": " << snackCount[i] << "包" << endl; } return 0; } ``` 我在以往的开发过程中,碰到过以下几点需要格外小心处理的地方: 输入验证必须严格,防止无效数据影响统计结果 循环结束条件要明确,避免无限循环 容器初始化确保所有种类都有默认值,避免访问未初始化的键 [2025-12-13 11:51:38 | AI写代码神器 | 248点数解答]

相关提问
发财导航,免费问AI
实用工具查看更多