Struct 介紹

實習講師 Jason

So far so good?

假設要寫一個統計學生段考成績的程式

芽芽幼兒園 奇異果班 🥝

一次段考考三科 = { 注音, 數數, 喊老師好 }

每科成績 ∈ [0, 100]

(三科平均 < 60) 或 (單科成績 < 40 分) 則**學費 Double**

### 三種操作 1. `init [stu_id]` 2. `score [stu_id] [sub_id] [score]` 3. `analysis`

You may do this


int stu_count = 0;
int stu_id[1000] = {};
int score[1000][3] = {};
double average[1000] = {};
bool fail[1000] = {};

void init(int stu_id){
    stu_id[stu_count] = stu_id;
    stu_count++;
}
						

void score(int sid, int bid, int score){
    for(int i = 0; i < stu_count; i++)
        if(stu_id[i] == sid)
            score[i][bid] = score;
}

void analysis(){
    for(int i = 0; i < stu_count; i++){
        for(int j = 0; j < 3; j++){
            average[i] += (double)score[i][j];
            if(score[i][j] < 40)  fail[i] = true;
        }
        average[i] /= 3;
        if(average[i] < 60.0)  fail[i] = true;
    }
}
						

So, what's the problem?

  • 表現性低
  • 擴展性低

How can we do it better?

Struct!

Define a struct


struct student {
    int id;
    int scores[3];
    double average;
    bool fail;
};
						

可以想像成定義一個新的型別

Usage


student jason;

jason.id = 1024;
jason.scores = {100, 100, 0};
jason.average = (double)(100 + 100 + 0)/3;
jason.fail = true;
						

✏️ 用點點來存取內部變數

Constructor 建構子


struct student {
    int id;
    int scores[3];
    double average;
    bool fail;

    student(int _id){
        id = _id;
    }
};

student jason(1024);

✏️ 方便初始化變數

Struct Inside Struct


struct exam {
    int id, score;
};

struct student {
    int id, exam_count;
    exam exams[1000];
    student(int _id){
        id = _id;
        exam_count = 0;
    }
};
						

✏️ 更優的資料抽象化

It's your turn now!

練習看看用 struct 來實作一個成績統計程式
p.s. 這個範圍沒有課堂練習呦❤️