C++:定义学生类,数据成员包含基本信息(姓名,学号,语文,外语,数学成绩)主函数声明10个学生类数组,并完成初始化,利用上节课学习内容,定义函数输出班级各科最高分与平均分
时间: 2023-05-31 21:07:07 浏览: 122
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name; // 姓名
string id; // 学号
double chinese; // 语文成绩
double english; // 外语成绩
double math; // 数学成绩
};
double max_score(double arr[], int size) { // 计算最高分
double max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
double avg_score(double arr[], int size) { // 计算平均分
double sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum / size;
}
int main() {
const int num_students = 10; // 学生人数
Student students[num_students] = {
{"张三", "1001", 89.5, 78.0, 92.0},
{"李四", "1002", 75.0, 82.5, 80.0},
{"王五", "1003", 92.5, 86.0, 85.5},
{"赵六", "1004", 68.0, 91.5, 76.0},
{"孙七", "1005", 80.5, 76.0, 88.5},
{"周八", "1006", 85.0, 90.0, 83.0},
{"吴九", "1007", 89.0, 78.5, 91.0},
{"郑十", "1008", 91.0, 85.0, 87.5},
{"钱十一", "1009", 76.5, 81.0, 79.0},
{"陈十二", "1010", 90.5, 87.5, 89.0}
};
// 计算各科最高分与平均分
double chinese_scores[num_students];
double english_scores[num_students];
double math_scores[num_students];
for (int i = 0; i < num_students; i++) {
chinese_scores[i] = students[i].chinese;
english_scores[i] = students[i].english;
math_scores[i] = students[i].math;
}
double max_chinese = max_score(chinese_scores, num_students);
double max_english = max_score(english_scores, num_students);
double max_math = max_score(math_scores, num_students);
double avg_chinese = avg_score(chinese_scores, num_students);
double avg_english = avg_score(english_scores, num_students);
double avg_math = avg_score(math_scores, num_students);
// 输出结果
cout << "班级语文最高分:" << max_chinese << endl;
cout << "班级外语最高分:" << max_english << endl;
cout << "班级数学最高分:" << max_math << endl;
cout << "班级语文平均分:" << avg_chinese << endl;
cout << "班级外语平均分:" << avg_english << endl;
cout << "班级数学平均分:" << avg_math << endl;
return 0;
}
阅读全文