c语言:定义一个学生结构体,并创建一个链表用于保存一个班级所有学生的基本信息,最后输出所有学生基本信息,以及班级的学生平均成绩。
时间: 2024-06-12 07:07:25 浏览: 12
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LEN 20
// 定义学生结构体
typedef struct student {
char name[MAX_NAME_LEN];
int age;
float score;
struct student *next;
} Student;
// 创建一个新的学生节点
Student *create_student(char *name, int age, float score) {
Student *new_student = (Student*)malloc(sizeof(Student));
if (new_student == NULL) {
printf("Error: memory allocation failed.\n");
exit(1);
}
strcpy(new_student->name, name);
new_student->age = age;
new_student->score = score;
new_student->next = NULL;
return new_student;
}
// 插入一个学生节点到链表中
void insert_student(Student **head, Student *new_student) {
if (*head == NULL) {
*head = new_student;
return;
}
Student *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_student;
}
// 打印所有学生的基本信息
void print_students(Student *head) {
if (head == NULL) {
printf("No students in the list.\n");
return;
}
printf("Name\tAge\tScore\n");
printf("---------------------\n");
Student *current = head;
float total_score = 0;
int count = 0;
while (current != NULL) {
printf("%s\t%d\t%.2f\n", current->name, current->age, current->score);
total_score += current->score;
count++;
current = current->next;
}
printf("---------------------\n");
printf("Average score: %.2f\n", total_score / count);
}
int main() {
Student *class_head = NULL;
// 创建学生节点并插入链表中
Student *s1 = create_student("Tom", 18, 89.5);
insert_student(&class_head, s1);
Student *s2 = create_student("Jerry", 19, 95.0);
insert_student(&class_head, s2);
Student *s3 = create_student("Alice", 20, 92.3);
insert_student(&class_head, s3);
// 打印所有学生的基本信息
print_students(class_head);
return 0;
}