1、某手机厂商对其在n个城市的销量进行统计分析,请定义sale类管理各省销量信息,使用sale类对象数组统计各省总销量及最高销量,要求在main()函数依次输入n个城市的省份名称、城市名称及销量,保证同一省份的数据将连续输入,输出各省的总销量及各省销量最高的城市名称及其销量。c++实现
时间: 2024-02-28 10:51:54 浏览: 36
下面是一个可能的 C++ 实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Sale {
public:
string province;
string city;
int quantity;
};
int main() {
int n;
cout << "请输入城市数量:";
cin >> n;
Sale* sales = new Sale[n];
for (int i = 0; i < n; i++) {
cout << "请输入第 " << i+1 << " 个城市的销量信息(格式:省份名称 城市名称 销量):";
cin >> sales[i].province >> sales[i].city >> sales[i].quantity;
}
// 统计各省总销量
string current_province = "";
int total_quantity = 0;
for (int i = 0; i < n; i++) {
if (sales[i].province != current_province) {
if (!current_province.empty()) {
cout << current_province << " 总销量:" << total_quantity << endl;
}
current_province = sales[i].province;
total_quantity = 0;
}
total_quantity += sales[i].quantity;
}
cout << current_province << " 总销量:" << total_quantity << endl;
// 统计各省最高销量
current_province = "";
int max_quantity = 0;
string max_city = "";
for (int i = 0; i < n; i++) {
if (sales[i].province != current_province) {
if (!current_province.empty()) {
cout << current_province << " 最高销量城市:" << max_city << " 销量:" << max_quantity << endl;
}
current_province = sales[i].province;
max_quantity = 0;
max_city = "";
}
if (sales[i].quantity > max_quantity) {
max_quantity = sales[i].quantity;
max_city = sales[i].city;
}
}
cout << current_province << " 最高销量城市:" << max_city << " 销量:" << max_quantity << endl;
delete[] sales;
return 0;
}
```
注意,这个实现中使用了动态内存分配,因为城市数量是在运行时输入的,无法在编译时确定数组大小。同时,为了方便起见,这里没有进行错误处理,例如输入的省份名称和城市名称不符合要求时程序会崩溃。如果需要使用此代码,需要自行增加错误处理的代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)