我找到了解决前面问题的代码,但是分数高低与总成绩哪里我该怎么加上去,我也不懂怎么加

#include <stdio.h> #include <stdlib.h> #include <string.h> #define SERIALLEN 20 #define COURSENUM 3 typedef struct { char course[SERIALLEN]; float score; }_courseInfo; typedef struct _stuinfo { char serial[SERIALLEN]; char name[SERIALLEN]; char sex[SERIALLEN]; _courseInfo courseInfo[COURSENUM]; struct _stuinfo *next; }stuinfo; int main(int argc, char **argv) { stuinfo *head=NULL,*ptr=NULL,*s=NULL; char str[SERIALLEN]; int cycle=1; int i=0; memset(str,0,SERIALLEN); printf("建立学生信息:\n"); head=(stuinfo *)calloc(1,sizeof(stuinfo)); if(!head) { perror("申请空间失败,没有足够内存。"); return -1; } ptr=head; while(cycle) { puts("输入学生学号(0退出):"); scanf("%s",str); if(strcmp(str,"0")) //如果学号为0,则退出链表的创建 { s=(stuinfo *)calloc(1,sizeof(stuinfo)); if(!ptr) { perror("申请空间失败,没有足够内存。"); return -1; } memset(s->serial,0,SERIALLEN); strcpy(s->serial,str); memset(s->name,0,SERIALLEN); puts("输入姓名:"); scanf("%s",s->name); memset(s->sex,0,SERIALLEN); puts("输入性别:"); scanf("%s",s->sex); for(i=0;i<COURSENUM;i++) { memset(s->courseInfo[i].course,0,SERIALLEN); puts("输入课程名称:"); scanf("%s",s->courseInfo[i].course); s->courseInfo[i].score=0.0f; puts("输入课程分数:"); scanf("%f",&(s->courseInfo[i].score)); } ptr->next=s; ptr=s; } else cycle=0; } ptr->next=NULL; ptr=head; head=head->next; free(ptr); //head=linkSort(head); ptr=head; printf("学号\t姓名\t性别"); for(i=0;i<COURSENUM;i++) printf("\t课程[%d]",i); printf("\n"); while(ptr!=NULL) { printf("%s\t%s\t%s",ptr->serial,ptr->name,ptr->sex); for(i=0;i<COURSENUM;i++) printf("\t%s[%.2f]",ptr->courseInfo[i].course,ptr->courseInfo[i].score); printf("\n"); ptr=ptr->next; } return 0; }

img

参考GPT和自己的思路:

在学生信息的结构体中已经定义了课程信息的结构体,每个学生的信息中包括了三门课的成绩,所以可以在遍历每个学生信息的时候,累加每门课的分数,再将总成绩赋值给该学生的一个新属性,如下修改代码:

typedef struct _stuinfo
{
    char serial[SERIALLEN];
    char name[SERIALLEN];
    char sex[SERIALLEN];
    _courseInfo courseInfo[COURSENUM];
    float totalScore; //添加一个总成绩属性
    struct _stuinfo *next;
} stuinfo;

...

while (ptr != NULL)
{
    ptr->totalScore = 0; //每次累加必须清零
    for (i = 0; i < COURSENUM; i++)
    {
        ptr->totalScore += ptr->courseInfo[i].score;
    }
    printf("%s\t%s\t%s\t%.2f\n", ptr->serial, ptr->name, ptr->sex, ptr->totalScore);
    ptr = ptr->next;
}

以上修改后的代码将会输出每个学生的总成绩。