第二週題目練習.pptx

資料結構實作

題目說明

輸入資料 data.txt

Untitled

1001 John 85.5 90.0 78.5 1002 Mary 76.0 88.5 92.0 1003 David 92.5 87.0 89.5 1004 Lisa 78.5 76.0 81.5 1005 Kevin 89.0 92.0 90.5 1006 Sarah 93.5 85.0 88.0 1007 Michael 81.0 78.0 87.5 1008 Jessica 87.0 89.5 95.0 1009 Andrew 90.5 82.0 79.0 1010 Emily 95.0 91.0 87.0 1011 Brian 84.0 76.5 83.5 1012 Olivia 88.5 92.0 91.5 1013 Christ 77.5 84.0 79.5 1014 Sophia 93.0 87.5 90.5 1015 Daniel 80.0 86.5 88.0 1016 Emma 89.5 90.0 92.0 1017 Ethan 82.5 79.5 83.0 1018 Mia 86.0 88.0 89.5 1019 Benn 91.5 94.0 90.5 1020 Ava 88.5 85.0 83.5

data.txt

輸出結果

Untitled

My Code:

D1131591.PNG

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

// class score 
struct scores {
    float chinese;
    float english;
    float math;
};

// class student
struct student {
    int id;
    char name[50];
    struct scores student_scores;
    float total_score;
    float average_score;
    int rank;
};

//Arrow operator -> , allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. 
//The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below.
//(pointer_name)->(variable_name) 
void Calculate(struct student *s) {
    s->total_score = s->student_scores.chinese + s->student_scores.english + s->student_scores.math;
    s->average_score = s->total_score / 3;
}

// rank, count who is better than me
void Rank(struct student students[], int n) {
    for (int i = 0; i < n; i++) {
        students[i].rank = 1;
        for (int j = 0; j < n; j++) {
            if (students[j].total_score > students[i].total_score) {
                students[i].rank++;
            }
        }
    }
}

int main() {
//	FILE is a variable in stdio.h
    FILE *file; 
    file = fopen("data.txt", "r");
    
//  null in stdlib.h
    if (file == NULL) {
        printf("The file can't open\\n");
        return 1;
    }

	    int n = 20; // student num
//	    create an array that is capable of storing 20 students 
	    struct student students[n]; 

    for (int i = 0; i < n; i++) {
        fscanf(file, "%d %s %f %f %f", &students[i].id, students[i].name,
               &students[i].student_scores.chinese, &students[i].student_scores.english,
               &students[i].student_scores.math);

        Calculate(&students[i]);
    }

    Rank(students, n);

    printf("ID\\tName\\tChinese\\tEnglish\\tMath\\tSum\\tAvg\\tRank\\n");
    for (int i = 0; i < n; i++) {
        printf("%d\\t%s\\t%.2f\\t%.2f\\t%.2f\\t%.2f\\t%.2f\\t%d\\n", students[i].id, students[i].name,
               students[i].student_scores.chinese, students[i].student_scores.english,
               students[i].student_scores.math, students[i].total_score,
               students[i].average_score, students[i].rank);
    }

    fclose(file);

    return 0;
}