请用C++完成以下代码:某班共有若干名学生,学生信息用如下的stuinfo结构表示,其中,男学生则gender取值为’m’,女学生则gender取值为’f’。2022年春季学期4门课程的成绩依次保存在score1~score4中。请编写函数int statistics(stuinfo stus[], int n)分别统计男生和女生的4门课程总成绩的最高分,其中stus数组存储了班上所有学生的信息,n为班上学生的总人数。函数最后返回男生总成绩最高分减去女生总成绩最高分的结果。 struct stuinfo { int id; // 学号 char name[10]; // 姓名 char gender; // 性别 int score1; // 课程1成绩 int score2; // 课程2成绩 int score3; // 课程3成绩 int score4; // 课程4成绩 }; int statistics(stuinfo stus[], int n)
时间: 2024-04-08 12:31:53 浏览: 153
Sure! Here's the implementation of the `statistics` function in C++:
```cpp
#include <iostream>
struct stuinfo {
int id; // 学号
char name[10]; // 姓名
char gender; // 性别
int score1; // 课程1成绩
int score2; // 课程2成绩
int score3; // 课程3成绩
int score4; // 课程4成绩
};
int statistics(stuinfo stus[], int n) {
int maxMaleScore = 0;
int maxFemaleScore = 0;
for (int i = 0; i < n; i++) {
if (stus[i].gender == 'm') {
if (stus[i].score1 > maxMaleScore) {
maxMaleScore = stus[i].score1;
}
if (stus[i].score2 > maxMaleScore) {
maxMaleScore = stus[i].score2;
}
if (stus[i].score3 > maxMaleScore) {
maxMaleScore = stus[i].score3;
}
if (stus[i].score4 > maxMaleScore) {
maxMaleScore = stus[i].score4;
}
} else if (stus[i].gender == 'f') {
if (stus[i].score1 > maxFemaleScore) {
maxFemaleScore = stus[i].score1;
}
if (stus[i].score2 > maxFemaleScore) {
maxFemaleScore = stus[i].score2;
}
if (stus[i].score3 > maxFemaleScore) {
maxFemaleScore = stus[i].score3;
}
if (stus[i].score4 > maxFemaleScore) {
maxFemaleScore = stus[i].score4;
}
}
}
return maxMaleScore - maxFemaleScore;
}
int main() {
// Example usage
stuinfo students[3] = {
{1, "Alice", 'f', 80, 90, 85, 95},
{2, "Bob", 'm', 70, 75, 80, 85},
{3, "Charlie", 'm', 90, 85, 95, 80}
};
int result = statistics(students, 3);
std::cout << "Difference between max male score and max female score: " << result << std::endl;
return 0;
}
```
In this example, I've provided a sample usage of the `statistics` function in the `main` function. You can modify it according to your needs. The function calculates the difference between the maximum score of male students and the maximum score of female students.
阅读全文