Struct (Brief Intro)

Sprout 2021/04/17

如果你是老師

想記錄學生的學習狀況

  • 姓名
  • 三次考試成績
  • 發言次數
  • 總分是否及格

直觀的方法 -- 開陣列

  • 姓名 ➜ char name[30][10]
  • 三次考試成績 ➜ float score[30][3]
  • 發言次數 ➜ int speak[30]
  • 總分是否及格 ➜ bool pass[30]

缺點:凌亂、不好整理

明明講的都是學生,能不能有一種資料型別叫做「學生」

忠班有 30 個學生

Recall: 陣列A可以放 30 個整數

➜ int A[30]

student zhong[30]

Struct -- student

  • 姓名
  • 三次考試成績
  • 發言次數
  • 總分是否及格
struct student{
    char name[30];
    float score[3];
    int speak;
    bool pass;
};
  • 記得分號!

宣告一個學生

#include <iostream>
#include <cstring>
using namespace std;

struct student{
    char name[30];
    float score[3];
    int speak;
    bool pass;
};

int main() {
    student freshman;
    strcpy(freshman.name, "John");
    freshman.score[0] = 72.3;
    freshman.score[1] = 85.0;
    freshman.score[2] = 90.5;
    freshman.speak = 5;
    freshman.pass = true;
}

宣告一群學生

#include <iostream>
#include <cstring>
using namespace std;

struct student{
    char name[30];
    float score[3];
    int speak;
    bool pass;
};

int main() {
    student zhong[30];
    strcpy(zhong[0].name, "John");
    zhong[0].score[0] = 72.3;
    zhong[0].score[1] = 85.0;
    zhong[0].score[2] = 90.5;
    zhong[0].speak = 5;
    zhong[0].pass = true;
}

小練習

  • struct 名稱:book
  • 包含:
    • 書名 (char)
    • 評分 (double)
    • 頁數 (int)
  • 宣告一本書,並印出其書名、評分和頁數

Solution

#include <iostream>
#include <cstring>

using namespace std;
struct book{
    char title[30];
    double score;
    int page;
};

int main() {
    book my_book;
    strcpy(my_book.title, "Harry Potter");
    my_book.score = 4.5;
    my_book.page = 350;

    cout << my_book.title << ":\n";
    cout << "score = " << my_book.score << "\n";
    cout << "page = " << my_book.page << "\n";
}

如果你是圖書館員

struct book{
    char title[30];
    double score;
    int page;
};

struct shelve{
    int id;
    int size;
    book books[100];
};

// 印出書架上s的第一本書的書名
// cout << s.books[0].title;

Struct (brief intro)

By hsutzu

Struct (brief intro)

Sprout 2021/04/17

  • 731