首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 學生成績查詢系統:陣列儲存、線性搜尋、平均/總分計算

     編輯:程式設計綜合問答

需求

全班學生數學成績:輸入資料 → 查詢單一學生 → 計算平均分、總分。資料量小,用陣列即可。

資料結構

struct Student {
    string name;
    int mathScore;
};

const int MAX_CLASS = 60;
Student classList[MAX_CLASS];
int studentCount = 0;

核心功能實作

1. 輸入資料(可硬編碼初始化)

void inputData() {
    // 範例:手動初始化
    classList[0] = {"Alice", 85};
    classList[1] = {"Bob", 92};
    classList[2] = {"Charlie", 78};
    studentCount = 3;
    // 或從檔案/控制台讀取
}

2. 查詢單一學生(線性搜尋)


int findStudent(const string& name) {
    for (int i = 0; i < studentCount; ++i) {
        if (classList[i].name == name) return i;
    }
    return -1; // 找不到
}

3. 計算平均分、總分


void calcStats(int& total, double& avg) {
    total = 0;
    for (int i = 0; i < studentCount; ++i) total += classList[i].mathScore;
    avg = studentCount > 0 ? (double)total / studentCount : 0.0;
}

4. 主選單


int main() {
    inputData();
    int choice;
    while (true) {
        cout << "1.查詢學生 2.顯示統計 3.離開\n選擇: ";
        cin >> choice;
        if (choice == 1) {
            string name; cout << "姓名: "; cin >> name;
            int idx = findStudent(name);
            if (idx >= 0) cout << name << " 數學: " << classList[idx].mathScore << endl;
            else cout << "查無此人\n";
        } else if (choice == 2) {
            int total; double avg;
            calcStats(total, avg);
            cout << "總分: " << total << " 平均: " << avg << endl;
        } else break;
    }
    return 0;
}

進階擴充

  • 多科目:`int scores[SUBJECT_COUNT];` 或 `map`。
  • 排序:`std::sort` 配合 lambda 按分數/名次排序。
  • 檔案持久化:`ofstream` 寫入 CSV,`ifstream` 讀取。
  • 動態容器:改用 `vector` 彈性擴充。

總結

小規模學生成績系統:**結構體陣列 + 線性搜尋 + 迴圈累加** 即可完美支援查詢、平均、總分。無需資料庫,專注核心邏輯與 C++ 基礎語法練習。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved