现有10个城市名,及春夏秋冬4个季节的平均温度值。编程定义结构体,输入10个城市名和四季平均温度,计算各城市的全年平均温度,并按温度由低到高的顺序输出城市名,4季温度及全年平均温度。
时间: 2023-02-21 22:34:30 浏览: 186
下面是简单的结构体定义代码:
```
struct City {
string name;
float spring;
float summer;
float autumn;
float winter;
float average;
};
void sortCities(City cities[], int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (cities[i].average > cities[j].average) {
City temp = cities[i];
cities[i] = cities[j];
cities[j] = temp;
}
}
}
}
int main() {
const int n = 10;
City cities[n];
for (int i = 0; i < n; i++) {
cout << "请输入第" << i + 1 << "个城市的名称:";
cin >> cities[i].name;
cout << "请输入第" << i + 1 << "个城市春季的平均温度:";
cin >> cities[i].spring;
cout << "请输入第" << i + 1 << "个城市夏季的平均温度:";
cin >> cities[i].summer;
cout << "请输入第" << i + 1 << "个城市秋季的平均温度:";
cin >> cities[i].autumn;
cout << "请输入第" << i + 1 << "个城市冬季的平均温度:";
cin >> cities[i].winter;
cities[i].average = (cities[i].spring + cities[i].summer + cities[i].autumn + cities[i].winter) / 4.0;
}
sortCities(cities, n);
cout << "城市名称\t春季\t夏季\t秋季\t冬季\t全年平均温度" << endl;
for (int i = 0; i < n; i++) {
cout << cities[i].name << "\t" << cities[i].spring << "\t" << cities[i].summer << "\t" << cities[i].autumn << "\t" << cities[i].winter << "\t" << cities[i].average << endl;
}
return 0;
}
```
该代码定义了一个结构体`City`,表示一个城市的名称和
阅读全文