学生平均成绩

时间:2020-07-11 10:12:55

标签: c

我必须计算每个学科每个学生的平均成绩。从文件中读取年级,学生和科目。结构是动态分配的。
这些文件如下所示:

students.txt

2, student1  
7, student2  
1, student3  

subject.txt

5, math  
3, physics  
8, geography  

grades.txt

日期,成绩等级
学生代码,学科代码,年级

18.06.2020, 3  
2, 3, 10  
1, 8, 7  
7, 5, 9  
19.06.2020, 2  
8, 3, 8  
3, 8, 6

2020年6月18日,代码为2的学生在代码为3的科目中获得10。

我将这些值存储在结构中

#define N 20
struct Subject {
    char subjectName[N];
    int code;
};
struct Students {
    char studentName[N];
    int code;
};
struct Grades {
    int grade[N][3];
    char date[N];
    int number_of_grades;   // number of grades in a day
};
struct Date {
    int number_of_days;     // total number of days
    int number_of_students; // total number of students
    int number_of_subjects; // total number of  subjects
}data;

这些是我用来从文件中读取值的函数。我用于其他用途的功能。

void filechack(FILE* f){
    if (f == NULL) {
        printf("The file cannot be opened");
        exit(1);
    }
}

struct Subject* subject() {
    struct Subject *ptr;
    int i;
    FILE *f = fopen("subject.txt", "r");
    filechack(f);
    ptr = NULL;
    for (i = 0; !feof(f); i++){
        ptr = realloc(ptr, sizeof(struct Subject)*(i+1));
        if (ptr == NULL){
            printf("Meomry not allocated");
            exit(1);
        }
        fscanf(f, "%d, %19s\n", &(ptr+i)->code, (ptr+i)->subjectName);
    }
    fclose(f);
    data.number_of_subjects = i;
    return ptr;
}

struct Students* students(){
    struct Students* ptr = NULL;
    int i;
    FILE *f = fopen("students.txt", "r");
    filechack(f);
    for (i = 0; !feof(f); i++){
        ptr = realloc(ptr, sizeof(struct Students)*(i+1));
        if (ptr == NULL){
            printf("Meomry not allocated");
            exit(1);
        }
        fscanf(f, "%d, %[^\n]", &(ptr+i)->code, (ptr+i)->studentName);
    }
    data.number_of_students = i;
    fclose(f);
    return ptr;
}

struct Grades* grades(){
    struct Grades* ptr = NULL;
    int i, j;
    FILE* f = fopen("grades.txt", "r");
    filechack(f);
    for(i = 0; !feof(f); i++){
        ptr = realloc(ptr, sizeof(struct Grades)*(i+1));
        if (ptr == NULL){
            printf("Meomry not allocated");
            exit(1);
        }
        fscanf(f, "%[^,], %d\n", (ptr+i)->date, &(ptr+i)->number_of_grades);
        for(j = 0; j<(ptr+i)->number_of_grades; j++){
            fscanf(f, "%d, %d, %d\n", &(ptr+i)->grade[j][0], &(ptr+i)->grade[j][1], &(ptr+i)->grade[j][2]);
        }
    }
    fclose(f);
    data.number_of_days = i;
    return ptr;
}

现在,我不知道如何才能找到每个学科每个学生的平均成绩。我认为最好的方法是将平均值存储在Student结构中,而不是将其打印到屏幕上。问题是我不知道该怎么做。也许您可以给我一些建议或技巧。

1 个答案:

答案 0 :(得分:1)

根据成绩所属的学生来存储成绩可能会有所帮助。您可以在Student结构中添加一个字段来保存其成绩,例如

struct Student {
    char studentName[N];
    int code;
    int *grades;
    int no_grades;
}

每次从文件中读取成绩时,您都可以搜索学生并将该成绩添加到相关学生下。这样,当您完成阅读后,便可以访问每个学生的成绩,并且计算平均值会容易得多。

希望这会有所帮助!