# C++ 1-5成績輸入 此專案使用C++ 結合C語言的輸入輸出法、函式、陣列等等 [TOC] ## 程式碼 ```cpp= #include <iostream> #include <cstdio> #include <string> using namespace std; string item[3] = {"國文", "英文", "專業"}; float scores[3][3]; void show(int sh_num); // 函式宣告 int main() { cout << "成績計算系統:" << endl << endl; for (int num = 0; num < 3; num++) { for (int i = 0; i < 3; i++) { printf("請輸入 %d 號 %s 成績(輸入完畢請按Enter):", (num + 1), item[i].c_str()); cin >> scores[num][i]; } system("CLS"); // 清除畫面 cout << "座號 \t國文 \t英文 \t專業 \t總分" << endl; //顯示上一號成績 show(num); } double total[3] = {0, 0, 0}; system("CLS"); // 清除畫面 cout << "座號 \t國文 \t英文 \t專業 \t總分" << endl; // 顯示總成績 for (int num = 0; num < 3; num++) { total[0] += scores[num][0]; total[1] += scores[num][1]; total[2] += scores[num][2]; show(num); } cout << "平均 \t" << (total[0]/3) << "\t" << (total[1]/3) << "\t" << (total[2]/3) << endl; system("pause"); return 0; } // 顯示單筆學生資料 void show(int sh_num){ double total1 = scores[sh_num][0] + scores[sh_num][1] + scores[sh_num][2]; printf("%d 號 \t%.2f \t%.2f \t%.2f \t%.2f\n", sh_num + 1, scores[sh_num][0], scores[sh_num][1], scores[sh_num][2], total1); } ``` ## 變數的宣告差異 * 變數宣告在main()外即可大家使用 * define為字元替代,將所有與變數名稱相同的都替代成宣告的 * const為不可變值的變數宣告 | 用法 | 是否有型別 | 可否改值 | 範圍 | 編譯階段行為 | |---------------------|----------|--------|------------------|------------------------------| | int x = 5 | ✅ | ✅ | 全域或區域皆可 | 正常變數 | | const int x = 5 | ✅ | ❌ | 全域或區域皆可 | 編譯器保護不能改值 | | #define X 5 | ❌ | ❌ | 無範圍限制 | 編譯前進行文字取代 | ## 函式的宣告位置 應該是寫在main()前面,而不是寫在後面 在 main() 前加上 void show(int sh_num); 可以改成程式碼加宣告都在main()前,或先在main()前宣告 再 後面寫程式碼 ## c_str()使用 %s 是char陣列模式,如果要輸出string陣列需要轉換 item[i].c_str() ```cpp= #include <cstdio> int main() { char name[50]; // 字串陣列 printf("請輸入你的名字:"); scanf("%s", name); printf("你好, %s!\n", name); return 0; } ```