全班學生數學成績:輸入資料 → 查詢單一學生 → 計算平均分、總分。資料量小,用陣列即可。
struct Student {
string name;
int mathScore;
};
const int MAX_CLASS = 60;
Student classList[MAX_CLASS];
int studentCount = 0;
void inputData() {
// 範例:手動初始化
classList[0] = {"Alice", 85};
classList[1] = {"Bob", 92};
classList[2] = {"Charlie", 78};
studentCount = 3;
// 或從檔案/控制台讀取
}
int findStudent(const string& name) {
for (int i = 0; i < studentCount; ++i) {
if (classList[i].name == name) return i;
}
return -1; // 找不到
}
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;
}
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;
}
小規模學生成績系統:**結構體陣列 + 線性搜尋 + 迴圈累加** 即可完美支援查詢、平均、總分。無需資料庫,專注核心邏輯與 C++ 基礎語法練習。