编写程序从键盘输入5个学生的信息,包括学生学号、姓名、性别、出生年月及成绩,用结构体数组保存学生的信息,要求用函数实现结构体数组的输入输出及求成绩最高学生的序号。
时间: 2023-12-16 09:16:25 浏览: 22
好的,下面是实现这个功能的 C++ 代码:
```c++
#include <iostream>
#include <string>
using namespace std;
// 定义学生结构体
struct Student {
int id; // 学号
string name; // 姓名
char gender; // 性别
string birth; // 出生年月
int score; // 成绩
};
// 输入学生信息函数
void input(Student stu_arr[], int n) {
for (int i = 0; i < n; i++) {
cout << "请输入第" << i+1 << "个学生的信息:" << endl;
cout << "学号:";
cin >> stu_arr[i].id;
cout << "姓名:";
cin >> stu_arr[i].name;
cout << "性别:";
cin >> stu_arr[i].gender;
cout << "出生年月:";
cin >> stu_arr[i].birth;
cout << "成绩:";
cin >> stu_arr[i].score;
}
}
// 输出学生信息函数
void output(Student stu_arr[], int n) {
for (int i = 0; i < n; i++) {
cout << "第" << i+1 << "个学生的信息如下:" << endl;
cout << "学号:" << stu_arr[i].id << endl;
cout << "姓名:" << stu_arr[i].name << endl;
cout << "性别:" << stu_arr[i].gender << endl;
cout << "出生年月:" << stu_arr[i].birth << endl;
cout << "成绩:" << stu_arr[i].score << endl;
}
}
// 求最高成绩学生序号函数
int max_score(Student stu_arr[], int n) {
int max_index = 0;
int max_score = stu_arr[0].score;
for (int i = 1; i < n; i++) {
if (stu_arr[i].score > max_score) {
max_index = i;
max_score = stu_arr[i].score;
}
}
return max_index;
}
int main() {
const int N = 5;
Student stu_arr[N];
input(stu_arr, N);
output(stu_arr, N);
int max_index = max_score(stu_arr, N);
cout << "成绩最高的学生是第" << max_index+1 << "个学生" << endl;
return 0;
}
```
这段程序定义了一个 `Student` 结构体,包括学生的学号、姓名、性别、出生年月和成绩。然后定义了三个函数,分别是 `input` 用于输入学生信息,`output` 用于输出学生信息,以及 `max_score` 用于求最高成绩学生的序号。在 `main()` 函数中,先定义一个长度为 5 的结构体数组,然后依次调用 `input`、`output` 和 `max_score` 函数,分别输入、输出和求最高成绩学生的序号。最后输出最高成绩学生的序号就完成了整个程序的功能。