其他分享
首页 > 其他分享> > (每日一练c语言)链式结构

(每日一练c语言)链式结构

作者:互联网

链式结构

定义一个学生结构体,并创建一个链表用于保存一个班级所有学生的基本信息,最后输出所有学生基本信息,以及班级的学生平均成绩。

#include <stdio.h>
#include <stdlib.h>

typedef struct Student
{
    char *name;
    int id;
    unsigned int age;
    char group;
    float score;
    struct Student *next;
} Student, *Class;

Class init_class()
{
    Class head;
    head = (Student *)malloc(sizeof(Student));
    if (!head)
        return NULL;
    head->next = NULL;
    return head;
}

void insert_student(Class cls, char *name, int id, unsigned int age, char group, float score)
{
    Class p;
    p = (Student *)malloc(sizeof(Student));
    p->name = name, p->id = id, p->age = age, p->group = group, p->score = score;
    p->next = cls->next;
    cls->next = p;
}

void print_class(const Class cls)
{
    Class prt = NULL;
    float total = 0, average = 0;
    int num_stu = 0;
    printf("=============== 学生基本信息 ===============\n");
    printf("姓名\t学号\t年龄\t小组\t成绩\n");
    printf("--------------------------------------------\n");
    for (prt = cls->next; prt; prt = prt->next)
    {
        printf("%s\t%d\t%d\t%c\t%.2f\n",
               prt->name, prt->id, prt->age, prt->group, prt->score);
        total += prt->score;
        ++num_stu;
    }
    printf("============================================\n");
    average = total / num_stu;
    printf("班级平均成绩:%.2f", average);
}

int main(int argc, char** argv)
{
    Class cls = init_class();
    insert_student(cls, "王五", 1003, 16, 'B', 80.50);
    insert_student(cls, "李四", 1002, 15, 'A', 90.00);
    insert_student(cls, "张三", 1001, 16, 'A', 95.50);

    print_class(cls);

    return 0;
}

标签:一练,int,每日,next,prt,Student,链式,Class,cls
来源: https://blog.csdn.net/dwf1354046363/article/details/122689243