c语言编写程序从键盘输入5个学生的信息,包括学生学号、姓名、性别、出生年月及成绩,用结构体数组保存学生的信息,要求用函数实现结构体数组的输入输出及求成绩最高学生的序号。
时间: 2023-12-16 16:15:42 浏览: 94
下面是一份实现上述要求的C语言程序:
```c
#include <stdio.h>
#include <string.h>
#define NUM_STUDENTS 5
// 定义学生结构体
struct student {
int id;
char name[20];
char gender;
int birth_year;
float score;
};
// 函数声明
void input_students(struct student *students, int n);
void output_students(struct student *students, int n);
int find_max_score(struct student *students, int n);
int main()
{
struct student students[NUM_STUDENTS];
input_students(students, NUM_STUDENTS);
output_students(students, NUM_STUDENTS);
int max_index = find_max_score(students, NUM_STUDENTS);
printf("The student with the highest score is %s, with a score of %.1f\n", students[max_index].name, students[max_index].score);
return 0;
}
// 输入学生信息的函数
void input_students(struct student *students, int n)
{
for (int i = 0; i < n; i++) {
printf("Please input the information of student %d:\n", i+1);
printf("ID: ");
scanf("%d", &students[i].id);
printf("Name: ");
scanf("%s", students[i].name);
printf("Gender (M/F): ");
scanf(" %c", &students[i].gender);
printf("Birth year: ");
scanf("%d", &students[i].birth_year);
printf("Score: ");
scanf("%f", &students[i].score);
}
}
// 输出学生信息的函数
void output_students(struct student *students, int n)
{
printf("=====================================\n");
printf("ID\tName\tGender\tBirth Year\tScore\n");
printf("=====================================\n");
for (int i = 0; i < n; i++) {
printf("%d\t%s\t%c\t%d\t\t%.1f\n", students[i].id, students[i].name, students[i].gender, students[i].birth_year, students[i].score);
}
printf("=====================================\n");
}
// 求成绩最高学生序号的函数
int find_max_score(struct student *students, int n)
{
int max_index = 0;
float max_score = students[0].score;
for (int i = 1; i < n; i++) {
if (students[i].score > max_score) {
max_score = students[i].score;
max_index = i;
}
}
return max_index;
}
```
这个程序使用了一个结构体数组`students`来保存学生信息。程序先调用`input_students`函数从键盘输入学生信息,并将结果保存到结构体数组中。然后调用`output_students`函数将学生信息输出到屏幕上。最后调用`find_max_score`函数求出成绩最高的学生的序号,并将结果输出到屏幕上。
阅读全文