--- title: 東華資管 tags: 進階程式設計考古題113 --- # 東華大學資管系進階程設113年考古 >老師:劉英和教授 >原文書:Problem Solving with C++ 10th(不重要,反正也用不到) >[初階程式設計113年考古](/8jRuMxB4SE63HLYweNa5RA) >[112年考古](https://hackmd.io/@sumo0711/BkqrQB_SR) :::danger 跟初階一樣阿,僅供參考,我裡面的幹話請忽略,不爽看就關掉 ::: # 進階實習題 ## Array 請寫一完整程式,當中宣告一個int array變數scores,長度為5,接著讓使用者輸入5個分數(皆為整數)分別儲存在scores的5個element中,接著求出這5個分數的平均值、最大值與最小值。 (需使用for loop存取各個element。) 提示:可以宣告三個變數分別記錄目前輸入的分數之中的最大值、最小值以及總和,每輸入一個分數就更新這三個變數。 ### Example Please input 5 scores: 10 20 30 40 50 The average is 30 The maximum is 50 The minimum is 10 ### ans ```cpp= #include <iostream> using namespace std; int main() { int scores[5]; int sum = 0; int maxScore = -1; int minScore = 101; cout << "Please input 5 scores:" << endl; for (int i = 0; i < 5; i++) { cin >> scores[i]; sum += scores[i]; if (scores[i] > maxScore) { maxScore = scores[i]; } if (scores[i] < minScore) { minScore = scores[i]; } } double average = static_cast<double>(sum) / 5; cout << "The average is " << average << endl; cout << "The maximum is " << maxScore << endl; cout << "The minimum is " << minScore << endl; return 0; } ``` ## 恩,陣列元素加五 請寫一完整程式,其中包含一個function為: void convert(int a[], int size) 在convert中,會使用for loop把 a 的每個element 值加 5。 在main function中,先宣告一大小為 3 的int array變數score,接著使用for loop讓使用者輸入score的 3 個element的值, 接著呼叫convert function,並把score及其大小 3 當做參數傳給convert,最後再使用for loop輸出score的 3 個element的值於螢幕上。 譬如使用者輸入三個值為 3, 10, 20,則會輸出8, 15, 25 (程式輸入、輸出資料前,請先輸出提示字串) ### Example Please input 3 scores: 3 10 20 The updated scores are: 8 15 25 ### ans ```cpp= #include <iostream> using namespace std; void convert(int a[], int size) { for (int i = 0; i < size; i++) { a[i] += 5; } } int main() { int score[3]; cout << "Please input 3 scores:" << endl; for (int i = 0; i < 3; i++) { cin >> score[i]; } convert(score, 3); cout << "The updated scores are:" << endl; for (int i = 0; i < 3; i++) { cout << score[i] << " "; } cout << endl; return 0; } ``` ## 函數輸入及顯示數字列表 請寫一完整程式,main function中宣告一個int array變數arr,長度為5 接著呼叫名為input_data的function讓使用者輸入最多5個數字存於arr的5個element中 若使用者輸入-1則代表輸入結束;input_data有三個參數 第一個參數是一個int array,第二個參數是一個int變數,其值代表第一個參數的長度,第三個參數是一個call-by-reference的int變數,在input_data中會將該變數的值設定為使用者輸入的數字的數量。 在main function,呼叫完input_data後,會再呼叫display這個function,在display function會把使用者輸入的值再輸出於螢幕上。 display有兩個參數,第一個參數是一個int array,第二個參數是一個int變數,其值代表第一個參數中有值的element的數量。 ### Example Please enter at most 5 numbers 179 25 25 -1 You input 179 25 25 ### ans ```cpp= #include <iostream> using namespace std; void input_data(int arr[], int size, int &count) { count = 0; cout << "Please enter at most 5 numbers:" << endl; for (int i = 0; i < size; i++) { int num; cin >> num; if (num == -1) { break; } arr[i] = num; count++; } } void display(int arr[], int count) { cout << "You input" << endl; for (int i = 0; i < count; i++) { cout << arr[i] << endl; } } int main() { int arr[5]; int count; input_data(arr, 5, count); display(arr, count); return 0; } ``` ## 2D Array 請寫一程式讓使用者輸入兩個學生各三次考試的成績(整數)。隨後計算每位學生三次考試的平均值並輸出最大平均值與最小平均值。(請使用2D array儲存成績) ### Example Please the scores of the #1 student: 70 80 90 Please the scores of the #2 student: 50 80 100 The maximum average is 80 The minimum average is 76 ### ans ```cpp= #include <iostream> using namespace std; int main() { int scores[2][3]; // 依題目,宣告 2D 陣列,儲存兩位學生的三次考試成績 int maxAverage = -1, minAverage = 101; // 初始化最大與最小平均分數 int sum, average; for (int i = 0; i < 2; i++) { cout << "Please the scores of the #" << (i + 1) << " student:" << endl; sum = 0; for (int j = 0; j < 3; j++) { cin >> scores[i][j]; sum += scores[i][j]; } average = sum / 3; if (average > maxAverage) { maxAverage = average; } if (average < minAverage) { minAverage = average; } } cout << "The maximum average is " << maxAverage << endl; cout << "The minimum average is " << minAverage << endl; return 0; } ``` ## Char Array 請撰寫一支程式,該程式讓使用者輸入姓名、性別、出生年月日(皆為不包含空格的字串,每個字串長度不超過512個字元) 使用者輸入後,程式再輸出此三項資訊。請用C-string(char array)儲存字串。 ### Example Please input your name, sex, and birthday: Einstein male 1879/3/14 Your name is Einstein Your sex is male Your Birthday is 1879/3/14 ### ans ```cpp= #include <iostream> using namespace std; int main() { const int MAX_LEN = 513; // 512字元 + '\0' char name[MAX_LEN]; char sex[MAX_LEN]; char birthday[MAX_LEN]; cout << "Please input your name, sex, and birthday:" << endl; cin.getline(name, MAX_LEN); cin.getline(sex, MAX_LEN); cin.getline(birthday, MAX_LEN); cout << "Your name is " << name << endl; cout << "Your sex is " << sex << endl; cout << "Your Birthday is " << birthday << endl; return 0; } ``` ## Char Array-2 (我真的很懶得取名子,你各位自己知道就好) 請撰寫一完整程式,當中宣告三個長度皆為512的 C-string(char array),名稱分別為str1, str2, str3 接著讓使用者輸入str1及str2的值(需要包含使用者輸入的空白) 之後程式會輸出str1是否等於str2(需輸出“equal” 或是 “not equal”於螢幕上) 接下來,將str2的值assign給str3,再把str1及str3的內容串接後輸出在螢幕上。 (假設不考量array長度是否足夠) ### Example Please input two strings: abc def not equal The concatenated string is abcdef ### ans ```cpp= #include <iostream> #include <cstring> using namespace std; int main() { const int LEN = 512; char str1[LEN]; char str2[LEN]; char str3[LEN]; cout << "Please input two strings:" << endl; cin.getline(str1, LEN); cin.getline(str2, LEN); if (strcmp(str1, str2) == 0) { cout << "equal" << endl; } else { cout << "not equal" << endl; } strcpy(str3, str2);//這部分在visual studio有機率會偵錯,若有則strcpy_s strcat(str1, str3);//這部分在visual studio有機率會偵錯,若有則strcat_s cout << "The concatenated string is " << str1 << endl; return 0; } ``` ## string 基本操作 請撰寫一完整程式,當中宣告三個data type為string的變數,名稱分別為str1, str2, str3。 接著讓使用者輸入str1及str2的值(需要包含使用者輸入的空白) 之後程式會輸出str1是否等於str2(需輸出“equal” 或是 “not equal”於螢幕上) 接下來,將str2的值assign給str3,再把str1及str3的內容串接後輸出在螢幕上。 再取出str1的字串中由第3個字元至第6個字元所組成的子句並輸出(提示:使用substr())。 (程式輸入、輸出資料前,請先輸出提示字串) ### Example Please input two strings: I am a student. You are student, too. not equal The concatenated string: I am a student.You are student, too. The sub-string: am a ### ans ```cpp= #include <iostream> #include <string> using namespace std; int main() { string str1, str2, str3; cout << "Please input two strings:" << endl; getline(cin, str1); getline(cin, str2); if (str1 == str2) { cout << "equal" << endl; } else { cout << "not equal" << endl; } str3 = str2; cout << "The concatenated string: " << str1 + str3 << endl; cout << "The sub-string: " << str1.substr(2, 4) << endl; return 0; } ``` ## 子字串搜尋 請撰寫一完整程式,當中宣告兩個data type為string的變數,名稱分別為str1, str2; 接著讓使用者輸入str1及str2的值(需要包含使用者輸入的空白)。之後,檢視str1中是否包含str2這個字串,若有包含,則輸出“The first string contains the second string”, 若無,則輸出“The first string does not contain the second string” (程式輸入、輸出資料前,請先輸出提示字串)。 ### Example Please input two strings: abc def The first string does not contain the second string ### ans ```cpp= #include <iostream> #include <string> using namespace std; int main() { string str1, str2; cout << "Please input two strings:" << endl; getline(cin, str1); getline(cin, str2); // 檢查 str2 是否出現在 str1 中 if (str1.find(str2) != string::npos) { cout << "The first string contains the second string" << endl; } else { cout << "The first string does not contain the second string" << endl; } return 0; } //npos 不是一個獨立的全域常數 //所以它必須透過 string::npos(或 std::string::npos)來存取 ``` ## Homewrok1-懶得命名1ლ(╹◡╹ლ) 請設計一完整的程式,讓使用者可以從鍵盤輸入兩串文字(包含空格),並使用兩個string 變數將這兩串文字儲存起來,接著開啟outfile.txt 這個檔案,並將兩串文字串接後(第二串文字串接在第一串文字之後),再把新串接得的字串再串接到第二串文字後,再輸出到outfile.txt 檔案中。 (讓使用者輸入資料前,請輸出提示字串) ### ans ```cpp= #include <iostream> #include <fstream> #include <string> #include <cstdlib> using namespace std; int main() { string str1, str2; cout << "Please input two strings:" << endl; getline(cin, str1); getline(cin, str2); string concat1 = str1 + str2; string finalResult = str2 + concat1; ofstream outfile("outfile.txt"); if (outfile.fail()) { cout << "ERR" << endl; exit(1); } outfile << finalResult << endl; outfile.close(); cout << "AC" << endl; return 0; } ``` ## Homework-2 假設檔案height.txt中記錄了一群人的身高,另一檔案weight.txt中記錄了這群人的體重,而身高、體重皆為帶小數的實數,檔案中每一行為一個數字,且最多記錄10個人的資料;請寫一支完整的程式,在main function中從檔案讀取這些人的身高、體重,且利用array變數來記錄這些資料,然後設計一個function BMI,BMI function 的參數為一個代表身高值的array、一個代表體重值的array,一個代表算得的BMI值的array、一個代表人數的int變數;在main function中呼叫BMI function來計算每個人的BMI,最後將算得的BMI值輸出在螢幕上,請輸出到小數點後3位。 (請注意,程式本身並不知道目前檔案中記錄幾個人的資料,只知道最多記錄10人。) (程式輸出資料前,請輸出提示字串) ### ans ```cpp= #include <iostream> #include <fstream> #include <iomanip> using namespace std; const int MAX = 10; // BMI function void BMI(double height[], double weight[], double bmi[], int n) { for (int i = 0; i < n; i++) { if (height[i] > 0) { bmi[i] = weight[i] / (height[i] * height[i]); } else { bmi[i] = 0; } } } int main() { double height[MAX], weight[MAX], bmi[MAX]; int count = 0; ifstream infileH("height.txt"); ifstream infileW("weight.txt"); if (infileH.fail() || infileW.fail()) { cout << "Error: cannot open file(s)." << endl; return 1; } // 同步讀取 height & weight while (count < MAX && infileH >> height[count] && infileW >> weight[count]) { count++; } infileH.close(); infileW.close(); BMI(height, weight, bmi, count); cout << "The BMI values are:" << endl; cout << fixed << setprecision(3); for (int i = 0; i < count; i++) { cout << "Person " << (i + 1) << ": " << bmi[i] << endl; } return 0; } ``` ### 承上題 3.承上題,請使用vector變數取代array,不限制檔案中所記錄的人數。 ### ans ```cpp= #include <iostream> #include <fstream> #include <vector> #include <iomanip> using namespace std; // BMI function void BMI(const vector<double>& height, const vector<double>& weight, vector<double>& bmi) { int n = height.size(); bmi.resize(n); for (int i = 0; i < n; i++) { if (height[i] > 0) { bmi[i] = weight[i] / (height[i] * height[i]); } else { bmi[i] = 0; } } } int main() { vector<double> height, weight, bmi; double h, w; ifstream infileH("height.txt"); ifstream infileW("weight.txt"); if (infileH.fail() || infileW.fail()) { cout << "Error: cannot open file(s)." << endl; return 1; } // 同步讀取 height & weight while (infileH >> h && infileW >> w) { height.push_back(h); weight.push_back(w); } infileH.close(); infileW.close(); BMI(height, weight, bmi); cout << "The BMI values are:" << endl; cout << fixed << setprecision(3); for (int i = 0; i < bmi.size(); i++) { cout << "Person " << (i + 1) << ": " << bmi[i] << endl; } return 0; } ``` ## Homework-3-三維陣列 請設計一完整程式,其中包含一個三維int陣列score,score陣列要記錄三個學生的四個科目各五次考試的成績,請在程式中讓使用者一一輸入這些成績,之後請計算下列數據並輸出在螢幕上: 每個學生在綜合這五次考試的各科平均成績 每個學生每次考試的四科平均成績 每個科目每次考試的三個學生平均成績 (讓使用者輸入及程式輸出資料前,請輸出提示字串) ```cpp= #include <iostream> #include <iomanip> using namespace std; int main() { int score[3][4][5]; // [學生][科目][考試次數] cout << "Input scores for 3 students, 4 subjects, 5 tests:" << endl; for (int s = 0; s < 3; s++) { for (int subj = 0; subj < 4; subj++) { for (int t = 0; t < 5; t++) { cin >> score[s][subj][t]; } } } cout << fixed << setprecision(2); cout << "\n[Each student's subject averages]" << endl; for (int s = 0; s < 3; s++) { cout << "Student " << s + 1 << ": "; for (int subj = 0; subj < 4; subj++) { double sum = 0; for (int t = 0; t < 5; t++) sum += score[s][subj][t]; cout << sum / 5 << " "; } cout << endl; } cout << "\n[Each student's test averages]" << endl; for (int s = 0; s < 3; s++) { cout << "Student " << s + 1 << ": "; for (int t = 0; t < 5; t++) { double sum = 0; for (int subj = 0; subj < 4; subj++) sum += score[s][subj][t]; cout << sum / 4 << " "; } cout << endl; } cout << "\n[Each subject's test averages]" << endl; for (int subj = 0; subj < 4; subj++) { cout << "Subject " << subj + 1 << ": "; for (int t = 0; t < 5; t++) { double sum = 0; for (int s = 0; s < 3; s++) sum += score[s][subj][t]; cout << sum / 3 << " "; } cout << endl; } return 0; } ``` ## ლ(╹◡╹ლ) 指向 請撰寫一完整程式,當中宣告一個data type為string的變數s1與一個data type為string的pointer變數s2,接著讓使用者輸入s1的值(包含空格),接著將s2指向s1,然後輸出s1與s2的值於螢幕上;接下來,利用new給予s2新的記憶體,再讓使用者輸入*s2的值(包含空格,注意可以儲存字串的是*s2,而不只是s2) ,再次輸出s1與s2的值於螢幕上。 (程式輸入、輸出資料前,請先輸出提示字串) ### Example Please input a string for s1: I am a student. The value of s1 and s2 are: I am a student. I am a student. Please input a string for s2: I am a teacher. The value of s1 and s2 are: I am a student. I am a teacher. ### ans ```cpp= #include <iostream> #include <string> using namespace std; int main() { string s1; string* s2; // string 型別的指標 cout << "Please input a string for s1:" << endl; getline(cin, s1); // s2 指向 s1 s2 = &s1; cout << "The value of s1 and s2 are:" << endl; cout << s1 << endl; cout << *s2 << endl; s2 = new string; cout << "\nPlease input a string for s2:" << endl; getline(cin, *s2); cout << "The value of s1 and s2 are:" << endl; cout << s1 << endl; cout << *s2 << endl; // 釋放記憶體 delete s2; return 0; } ``` ## vector和平方根 請撰寫一完整程式,當中宣告一個base type為int的vector變數vec,接下來請使用者決定要輸入幾個整數值後,再讓使用者輸入這些值並存在vec中。接著將每個值開根號後輸出於螢幕上。 (程式輸入、輸出資料前,請先輸出提示字串) ### Example Please specify the number of integers you would like to enter. 5 Please enter 5 integers: 78 563 214 89 711 The square roots of the entered numbers are as follows. 8.83176 23.7276 14.6287 9.43398 26.6646 ### ans ```cpp= #include <iostream> #include <vector> #include <cmath> using namespace std; int main() { int n; vector<int> vec; cout << "Please specify the number of integers you would like to enter." << endl; cin >> n; cout << "Please enter " << n << " integers:" << endl; for (int i = 0; i < n; i++) { vec.push_back(0); // 先放一個預設值 cin >> vec.back(); // 直接讀入最後一個元素 } cout << "The square roots of the entered numbers are as follows." << endl; for (int i = 0; i < n; i++) { cout << sqrt(vec[i]) << endl; } return 0; } ``` ## 開讀檔字串分流輸出 請撰寫一完整程式,當中有一vector 變數為str,而str 所儲存的資料形別為string,接著從檔案infile.txt讀入未知個數的的字串(請使用getline這個function),一一以str來儲存。然後將 str[1], str[3], str[5],…輸出至outfile1.txt中,而str[0], str[2], str[4],…輸出至outfile2.txt中。(開啟檔案不需檢查是否成功) ### ans ```cpp= #include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; int main() { vector<string> str; ifstream infile("infile.txt"); // 我其實自己通常都是用絕對路徑 ofstream outfile1("outfile1.txt");//因為電腦教室的路徑很難找 ofstream outfile2("outfile2.txt"); string line; while (getline(infile, line)) { str.push_back(line); } for (int i = 0; i < str.size(); i++) { if (i % 2 == 0) { outfile2 << str[i] << endl; } else { outfile1 << str[i] << endl; } } return 0; } ``` ## 指標:輸入與判斷ฅ՞•ﻌ•՞ฅ ### 知道現在幾點嗎,凌晨三點。 請撰寫一完整程式,當中宣告一個data type為string的變數s1與一個data type為string的pointer變數s2,接著讓使用者輸入s1的值(包含空格),接著將s2指向s1,然後輸出s1與*s2的值於螢幕上;接下來,利用new給予s2新的記憶體,再讓使用者輸入*s2的值(包含空格,注意可以儲存字串的是*s2,而不只是s2) ,再次輸出s1與*s2的值於螢幕上。並輸出s1的值中是否包含*s2的值(輸出Yes或是No)。 (程式輸入、輸出資料前,請先輸出提示字串) ### Example Please input a string for s1: I am a student. The value of s1 and s2 are: I am a student. I am a student. Please input a string for s2: I am a teacher. The value of s1 and s2 are: I am a student. I am a teacher. No ### ans ```Cpp= #include <iostream> #include <string> using namespace std; int main() { string s1; string* s2; // 這東西是宣告指標,每次我都忘記 cout << "Please input a string for s1:" << endl; getline(cin, s1); s2 = &s1; cout << "The value of s1 and s2 are:" << endl; cout << s1 << endl; cout << *s2 << endl << endl; s2 = new string; cout << "Please input a string for s2:" << endl; getline(cin, *s2); cout << "The value of s1 and s2 are:" << endl; cout << s1 << endl; cout << *s2 << endl; if (s1.find(*s2) != string::npos) { cout << "Yes" << endl; } else { cout << "No" << endl; } delete s2; return 0; } ``` ## Dynamic array 請撰寫一完整程式,該程式可讓使用者輸入若干學生各若干個考試的成績(成績為整數),並求出每個學生的平均成績。程式一開始先讓使用者輸入學生人數以及考試次數(假設使用者輸入n個學生與m次考試),接著宣告一個2維的dynamic array(維度分別為n與m),然後讓使用者輸入每個學生每次考試的成績儲存於該2維陣列中,最後計算每個學生的平均成績並輸出在螢幕上。(程式輸入、輸出資料前,請先輸出提示字串,此題不需刪除記置的記憶體。) ### Example Please input the number of students and the number of exams. 3 2 Please input the score of exam#1 of the student#1: 80 Please input the score of exam#2 of the student#1: 100 Please input the score of exam#1 of the student#2: 50 Please input the score of exam#2 of the student#2: 60 Please input the score of exam#1 of the student#3: 85 Please input the score of exam#2 of the student#3: 91 The average score of the student#1 is 90 The average score of the student#2 is 55 The average score of the student#3 is 88 ### ans ```cpp= #include <iostream> using namespace std; int main() { int n, m; cout << "Please input the number of students and the number of exams." << endl; cin >> n >> m; // 二維動態陣列 (n 個學生,每人 m 次考試) int** scores = new int*[n]; for (int i = 0; i < n; i++) { scores[i] = new int[m]; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << "Please input the score of exam#" << j + 1 << " of the student#" << i + 1 << ":" << endl; cin >> scores[i][j]; } } for (int i = 0; i < n; i++) { int sum = 0; for (int j = 0; j < m; j++) { sum += scores[i][j]; } int avg = sum / m; cout << "The average score of the student#" << i + 1 << " is " << avg << endl; } return 0; } ``` ## 宣告struct 車車 請撰寫一完整程式,當中宣告一struct名為Car,該struct包含兩個public data member,其一為data type為string的name,其二為data type為int的displacement。接著在main function中宣告一個Car變數YourCar,並讓使用者填入車的資料(名字及排氣量),最後再將使用者輸入的值一一輸出在螢幕上。 (程式輸入、輸出資料前,請先輸出提示字串) ### Example Please input the name and displacement of your car: Mondeo 2000 The name of your car is Mondeo The displacement of your car is 2000 ### ans ```cpp= #include <iostream> #include <string> using namespace std; struct Car { public: string name; int displacement; }; int main() { Car YourCar; cout << "Please input the name and displacement of your car:" << endl; cin >> YourCar.name >> YourCar.displacement; cout << "The name of your car is " << YourCar.name << endl; cout << "The displacement of your car is " << YourCar.displacement << endl; return 0; } ``` ## 巢狀 struct 與 vector 儲存 請撰寫一完整程式,當中定義一struct名為Car,該struct包含兩個member variable,其一為data type為string的name,其二為data type為int的displacement。另定義一struct名為PersonInfo,該struct包含兩個member variable,其一為data type為string的變數name,其二為data type為Car的變數OwnCar。 在main function中宣告一base type為PersonInfo的vector變數,並讓使用者輸入兩個人的資料(name與OwnCar這兩個member variable的值)存於該vector變數中,最後再輸出所輸入的資料。(提示:使用 push_back 這個 member function 將一個 PersonInfo 的變數輸入所宣告的 vector 變數中。) ### Example Please input info of two people: Input the name and car data of the first person: Andy Kuga 2000 Input the name and car data of the second person: Bob Altis 1800 The name and car data of the two people are: Andy Kuga 2000 Bob Altis 1800 ### ans ```cpp= #include <iostream> #include <vector> #include <string> using namespace std; struct Car { string name; int displacement; }; struct PersonInfo { string name; Car OwnCar; }; int main() { vector<PersonInfo> people; cout << "Please input info of two people:" << endl; for (int i = 0; i < 2; i++) { PersonInfo p; if (i == 0) { cout << "Input the name and car data of the first person:" << endl; } else { cout << "Input the name and car data of the second person:" << endl; } cin >> p.name; cin >> p.OwnCar.name; cin >> p.OwnCar.displacement; people.push_back(p); cout << endl; } cout << "The name and car data of the two people are:" << endl; for (int i = 0; i < people.size(); i++) { cout << people[i].name << endl; cout << people[i].OwnCar.name << endl; cout << people[i].OwnCar.displacement << endl; cout << endl; } return 0; } ``` ## Car和 class 和 member variable 請撰寫一完整程式,當中定義一class名為Car,該class包含兩個member variable,其一為data type為string的name,其二為data type為int的displacement。並且加入一member function為 Input,其沒有回傳值,沒有參數,在Input中,會讓使用者輸入name及 displacement 的值。另有兩 member function為 get_name及get_displacement,分別回傳 name及 displacement的值。(請將member function設定為public,member variable設定為private) 接著,在main function中請宣告一個Car的變數 YourCar,並讓使用者填入車的資料(名字及排氣量),最後再將使用者輸入的值一一輸出在螢幕上。(提示:呼叫Input function以讓使用者輸入車的資料,呼叫 get_name 與 get_displacement 取出車的資料。) ### Example Please input the name and displacement of your car: Sentra 1600 The name of your car is Sentra The displacement of your car is 1600 ### ```cpp= #include <iostream> #include <string> using namespace std; class Car { private: string name; int displacement; public: void Input() { cout << "Please input the name and displacement of your car:" << endl; cin >> name >> displacement; } string get_name() { return name; } int get_displacement() { return displacement; } }; int main() { Car YourCar; YourCar.Input(); cout << "The name of your car is " << YourCar.get_name() << endl; cout << "The displacement of your car is " << YourCar.get_displacement() << endl; return 0; } ``` ## 程設都是閱讀測驗,此篇為閱讀測驗-1 請撰寫一完整程式,當中定義一class名為Car,該class包含兩個member variable,其一為data type為string的name,其二為data type為int的displacement。並且加入一member function為 Input,其沒有回傳值,沒有參數,在Input中,會讓使用者輸入name及 displacement 的值。另有兩 member function為 get_name及get_displacement,分別回傳 name及 displacement的值。(請將member function設定為public,member variable設定為private) Car有一default constructor,其中會把name的值設為空字串(“”),把displacement的值設為0。另有一constructor有兩個參數,兩個參數分別是data type為string的 model_name 跟 data type為 int 的model_displacement,在該constructor中,會把 name 跟 displacement 的值分別設定為 model_name及 model_displacement 的值。 接著,在main function中請宣告一個Car的變數 YourCar,並讓使用者填入車的資料(名字及排氣量),最後再將使用者輸入的值一一輸出在螢幕上。另宣告一個Car變數MyCar,其宣告為 Car MyCar(Kuga, 2000); 隨後也輸出該變數的兩個member variable的值於螢幕上。 (程式輸入、輸出資料前,請先輸出提示字串) ### Example Please input the name and displacement of your car: Sentra 1600 The name of your car is Sentra The displacement of your car is 1600 The name of my car is Kuga The displacement of my car is 2000 ### ans ```cpp= #include <iostream> #include <string> using namespace std; class Car { private: string name; int displacement; public: // Default constructor Car() { name = ""; displacement = 0; } // Constructor with parameters Car(string model_name, int model_displacement) { name = model_name; displacement = model_displacement; } // Member function for input void Input() { cout << "Please input the name and displacement of your car:" << endl; cin >> name >> displacement; } // Getter functions string get_name() { return name; } int get_displacement() { return displacement; } }; int main() { Car YourCar; YourCar.Input(); cout << "The name of your car is " << YourCar.get_name() << endl; cout << "The displacement of your car is " << YourCar.get_displacement() << endl; Car MyCar("Kuga", 2000); cout << "The name of my car is " << MyCar.get_name() << endl; cout << "The displacement of my car is " << MyCar.get_displacement() << endl; return 0; } ``` ## 哈哈,閱讀測驗2 請設計一class名為Money,其有兩個member variable,分別為data type為string的Currency與float的Amount,分別代表幣別與金額。其default constructor將兩個member variable分別設為NT與0。另有一包含兩個參數的constructor,其將兩參數的值分別設定給兩個member variable。該程式為Money重載(overload)+(加號)、 -(減號)、>> 與 << 這四個符號。 重載加號有兩個Money的參數,會回傳一Money變數,其運作方式如下: 先檢查兩個Money參數的幣別是否一致,假設幣別只有兩種,一為USD,一為NT,若兩參數的幣別一致,則回傳值(為一Money變數)的Currency之值為參數的Currency值,而回傳值的Amount之值為兩個Money參數的金額(Amount變數)的加總值。 若兩參數的幣別不同(一為USD,一為NT),先將回傳值(為一Money變數)的Currency之值設為NT,再將幣別為USD的參數其Amount變數的值乘以31後(即轉成新台幣)並加上另一參數(其幣別原本就為NT)的Amount之值,以該加總值做為回傳值之Amount之值。 重載減號亦有兩個Money參數,其處理原則與Add相同,唯一不同在於回傳值的Amount值為第一個參數之Amount值減去第二個參數之Amount值(記得若兩個參數的幣別不同,要先轉成新台幣)。 重載 >> 讓使用者輸入兩個member variable的值。 重載 << 會輸出一Money變數之Currency與Amount的值。 Money另有兩個public member function分別為GetCurrency與GetAmount,分別回傳Currency與Amount的值。 請於main function中宣告兩個Money變數,一個沒有參數(使用default constructor),一個有參數(“NT”, 300),並讓使用者輸入第一個Money變數的兩個member variable的值,最後輸出兩個Money變數的總和與第一個Money變數減去第二個Money變數的值(需使用重載的四個符號完成上述要求。) ### Example Please input currency and amount: USD 90 The sum is NT 3090 ! The difference is NT 2490 ! ### ans ```cpp= #include <iostream> #include <string> using namespace std; class Money { private: string Currency; float Amount; public: Money() { Currency = "NT"; Amount = 0; } Money(string c, float a) { Currency = c; Amount = a; } string GetCurrency() const { return Currency; } float GetAmount() const { return Amount; } friend Money operator+(const Money& m1, const Money& m2) { Money result; if (m1.Currency == m2.Currency) { result.Currency = m1.Currency; result.Amount = m1.Amount + m2.Amount; } else { result.Currency = "NT"; if (m1.Currency == "USD") { result.Amount = m1.Amount * 31 + m2.Amount; } else { result.Amount = m1.Amount + m2.Amount * 31; } } return result; } friend Money operator-(const Money& m1, const Money& m2) { Money result; if (m1.Currency == m2.Currency) { result.Currency = m1.Currency; result.Amount = m1.Amount - m2.Amount; } else { result.Currency = "NT"; if (m1.Currency == "USD") { result.Amount = m1.Amount * 31 - m2.Amount; } else { result.Amount = m1.Amount - m2.Amount * 31; } } return result; } friend istream& operator>>(istream& in, Money& m) { in >> m.Currency >> m.Amount; return in; } friend ostream& operator<<(ostream& out, const Money& m) { out << m.Currency << " " << m.Amount; return out; } }; int main() { Money m1; Money m2("NT", 300); cout << "Please input currency and amount:" << endl; cin >> m1; Money sum = m1 + m2; Money diff = m1 - m2; cout << "The sum is " << sum << " !" << endl; cout << "The difference is " << diff << " !" << endl; return 0; } ``` ## Homework2-下面這串鬼東西在簡報上21頁 一本日記本包含作者名字與一篇篇的日記,每篇日記有日期與日記本文的部份,請用struct設計一個data type代表一篇日記,其名為Diary,其中年、月、日皆為int變數,日記本文是string變數;再用struct設計一個 data type代表一本日記本,其名為DiaryBook其中作者名字為長度為32的char陣列,日記為一data type是Diary的vector變數。 在main function中,宣告一個DiaryBook的變數,先讓使用者輸入作者名字,接著問使用者要輸入幾篇日記,再讓使用者輸入每篇日記的年、月、日與日記本文,最後輸出作者名字與每篇日記的日期與本文。 (讓使用者輸入及程式輸出資料前,請輸出提示字串) ### Example Please input your name: Tom How many diaries do you want to input? 2 Please input diary #0: which year? 2015 which month? 5 which day? 10 the content? I feel good today. Please input diary #1: which year? 2015 which month? 5 which day? 11 the content? I feel bad today. Your name is Tom. The date of diary #0 is 2015.5.10 Its content is I feel good today. The date of diary #1 is 2015.5.11 Its content is I feel bad today. ### ans ```cpp= #include <iostream> #include <vector> #include <string> using namespace std; struct Diary { int year; int month; int day; string content; }; struct DiaryBook { char author[32]; vector<Diary> diaries; }; int main() { DiaryBook myBook; cout << "Please input your name:" << endl; cin.getline(myBook.author, 32); int n; cout << "How many diaries do you want to input?" << endl; cin >> n; cin.ignore(); for (int i = 0; i < n; i++) { Diary d; cout << "Please input diary #" << i << ":" << endl; cout << "which year?" << endl; cin >> d.year; cout << "which month?" << endl; cin >> d.month; cout << "which day?" << endl; cin >> d.day; cin.ignore(); cout << "the content?" << endl; getline(cin, d.content); myBook.diaries.push_back(d); } cout << endl; cout << "Your name is " << myBook.author << "." << endl; for (int i = 0; i < myBook.diaries.size(); i++) { cout << "The date of diary #" << i << " is " << myBook.diaries[i].year << "." << myBook.diaries[i].month << "." << myBook.diaries[i].day << endl; cout << "Its content is " << myBook.diaries[i].content << endl; } return 0; } ``` ## 呈上題 2.一本日記本包含作者名字與一篇篇的日記,每篇日記有日期與日記本文的部份,請用struct設計一個data type代表一篇日記,其名為Diary,其中年、月、日皆為int變數,日記本文是string變數;再用class設計一個 data type代表一本日記本,其名為DiaryBook,其中作者名字是data type為char的pointer變數Name,儲存一篇篇日記的變數為一data type是Diary的vector變數Diaries。 其有一default constructor會把Name宣告為長度是32的dynamic array,並且內容設為空字串。另有一含有一個char陣列為參數的constructor,會將Name宣告為長度是該參數內容的長度的dynamic array,並將該參數的內容複製給Name。 其有一copy constructor,含有一個data type為DiaryBook的const call-by-reference的參數,當中會把參數的兩個member variable的值分別assign給Name與Diaries,請注意要為Name配置記憶體。 其有一destructor,會將配置給Name的記憶體回收。 其重載了assign (=)這個符號,含有一個data type為DiaryBook的const call-by-reference的參數,當中會把參數的兩個member variable的值分別assign給Name與Diaries,請注意要為Name配置記憶體。 其有一public function稱為InputName,沒有回傳值,含有一個參數為char陣列的const變數,會將該參數的內容複製給Name。 此外,其有一public function為InputDiary,沒有回傳值,有一data type為Diary的const call-by-reference參數OneDiary,在InputDiary中,會把OneDiary輸入Diaries中。 另有一public function為Output,沒有參數及回傳值,其會輸出日記本的作者名字與每篇日記的年、月、日與內容。 接著,使用friend function為DiaryBook這個data type重新定義 == 這個符號,其會比較兩本日記本的作者姓名與日記內容是否相同,若作者姓名一樣且日記篇數一樣,並且每篇日記的年、月、日與內容都相同的話,則回傳true,不然則回傳false。 在main function中,先宣告一個DiaryBook的變數,宣告時直接給一參數"Tom",接著問使用者要輸入幾篇日記,再讓使用者輸入每篇日記的年、月、日與日記本文;接著宣告第二個DiaryBook變數,但沒有初始值,接著讓使用者輸入第二本日記的作者名字,然後問使用者要輸入幾篇日記,再讓使用者輸入每篇日記的年、月、日與日記本文。 接著宣告第三個DiaryBook變數,其宣告時就將第一個DiaryBook變數assign給它,最後宣告第四個DiaryBook變數,宣告時沒有初始值,但隨後立刻將第二個DiaryBook變數assign給它。 最後輸出四本日記的作者名字與每篇日記的日期與本文,然後再輸出第三本與第四本日記是否相同。 (讓使用者輸入及程式輸出資料前,請輸出提示字串) ### Example Tom, How many diaries do you want to input for the first diary book? 2 Please input diary #0: which year? 2001 which month? 1 which day? 1 the content? I feel good. Please input diary #1: which year? 2001 which month? 1 which day? 2 the content? I feel bad. Please input a name for the second diary book: Mary How many diaries do you want to input? 2 Please input diary #0: which year? 2002 which month? 2 which day? 2 the content? I feel good. Please input diary #1: which year? 2002 which month? 2 which day? 3 the content? I feel bad. The first diary book: The author is Tom The date of diary #0 is 2001.1.1 Its content is I feel good. The date of diary #1 is 2001.1.2 Its content is I feel bad. The second diary book: The author is Mary The date of diary #0 is 2002.2.2 Its content is I feel good. The date of diary #1 is 2002.2.3 Its content is I feel bad. The third diary book: The author is Tom The date of diary #0 is 2001.1.1 Its content is I feel good. The date of diary #1 is 2001.1.2 Its content is I feel bad. The fourth diary book: The author is Mary The date of diary #0 is 2002.2.2 Its content is I feel good. The date of diary #1 is 2002.2.3 Its content is I feel bad. The two diary books are not identical. ## 呈上上題 3. 請撰寫一完整程式,當中定義一class名為Car,該class包含兩個member variable,其一為data type為string的name,其二為data type為int的displacement。並且加入一member function為 Input,其沒有回傳值,沒有參數,在Input中,會讓使用者輸入name及 displacement 的值。另有兩 member function為 get_name及get_displacement,分別回傳 name及 displacement的值。(請將member function設定為public,member variable設定為private) Car有一default constructor,其中會把name的值設為空字串(“”),把displacement的值設為0。另有一constructor有兩個參數,兩個參數分別是data type為string的 model_name 跟 data type為 int 的model_displacement,在該constructor中,會把 name 跟 displacement 的值分別設定為 model_name及 model_displacement 的值。 接著,在main function中請宣告一個Car的變數 YourCar,並讓使用者填入車的資料(名字及排氣量),最後再將使用者輸入的值一一輸出在螢幕上。另宣告一個Car變數MyCar,其宣告為 Car MyCar(Kuga, 2000); 隨後也輸出該變數的兩個member variable的值於螢幕上。 (程式輸入、輸出資料前,請先輸出提示字串) 以上請將題目需求分別以class的header file、implementation file及application file的方式實作。 在header file中請加上 #ifndef, #define, #endif ### example Please input the name and displacement of your car: Sentra 1600 The name of your car is Sentra The displacement of your car is 1600 The name of my car is Kuga The displacement of my car is 2000 ### ans,我把它放在一起,自己拆開 如果看不懂要拆哪的話,代表你應該解不出這題 ```cpp= // car.h #ifndef CAR_H #define CAR_H #include <string> using namespace std; class Car { private: string name; int displacement; public: Car(); Car(string mn, int md); void Input(); string get_name(); int get_displacement(); }; #endif //car.cpp (implementation) #include "Car.h" #include <iostream> using namespace std; Car::Car():name(""),displacement(0){} Car::Car(string mn,int md):name(mn),displacement(md){} void Car::Input(){cin>>name>>displacement;} string Car::get_name(){return name;} int Car::get_displacement(){return displacement;} //main.cpp #include <iostream> #include "Car.h" using namespace std; int main(){ Car YourCar; cout<<"Please input the name and displacement of your car:"<<endl; YourCar.Input(); cout<<"The name of your car is "<<YourCar.get_name()<<endl; cout<<"The displacement of your car is "<<YourCar.get_displacement()<<endl; Car MyCar("Kuga",2000); cout<<"The name of my car is "<<MyCar.get_name()<<endl; cout<<"The displacement of my car is "<<MyCar.get_displacement()<<endl; return 0; } ``` ## h2 請設計一完整程式,其中包含一個class名為Animal,Animal有三個private member variable,其一是data type是char*的變數,名為Name,其二是data type為int的變數MaxLength,其三是data type為int的變數,名為NumOfLegs。 Animal有一default constructor,其將MaxLength的值設定為32,而將Name宣告為長度是(MaxLength + 1)的dynamic array,並將字串內容設定為空字串(""),NumOfLegs設定為-1。 其有一個含有兩個參數的constructor,第一個參數為data type為char []的const變數_N,第二個參數為data type為int的const變數 _L,在該constructor中,會將MaxLength的值設定為_N內含字串內容的長度,並將Name宣告為長度是(MaxLength + 1)的dynamic array,且將 _N與 _L的值分別assign給Name與NumOfLegs。 其有一個copy constructor,有一個data type為Animal&的const變數 _Ani,會將MaxLength的值設定為_Ani.Name內含字串內容的長度,並將Name宣告為長度是(MaxLength + 1)的dynamic array ,且將 _Ani.Name與 _Ani.NumOfLegs的值分別assign給Name與NumOfLegs。 其另有一destructor,會將配置給Name的記憶體回收。 接著為Animal重載(overload)<<與>>這兩個運算子(operator),分別會讓使用者輸入與輸出兩個member variable的值,其可以從鍵盤或是檔案輸入,也可以輸出至螢幕或是檔案。其中輸入時可以允許空格,並且最多輸入MaxLength這麼多個字元。 再為Animal重載 == 這個符號,其回傳值為bool,有兩個Animal的參數,其會比較兩個參數的Name與NumOfLegs的值是否相等,若皆相等,則回傳true,否則就回傳false。 在mail function中,請宣告兩個Animal變數如下: Animal FirstAnimal("Dog", 4), SecondAnimal; 然後讓使用者輸入SecondAnimal的兩個member variable的值,接著再宣告另一個Animal變數如下: Animal ThirdAnimal = SecondAnimal; 隨後輸出三個動物的名字與腳的數量於螢幕上後 ,再比較FirstAnimal與ThirdAnimal是否相等。 可在程式碼開頭處加上 #define _CRT_SECURE_NO_WARNINGS 以避免 Error C4996 ### Example Please input name and number of legs of an animal: Horse 4 The name and number of legs of the first animal are: name is Dog, number of legs is 4 The name and number of legs of the second animal are: name is Horse, number of legs is 4 The name and number of legs of the third animal are: name is Horse, number of legs is 4 They are not equal! ### ans ```cpp= #define _CRT_SECURE_NO_WARNINGS //題目說可以放的,我也不知道為什麼 #include <iostream> #include <cstring> #include <string> using namespace std; class Animal { private: char* Name; int MaxLength; int NumOfLegs; public: Animal() { MaxLength = 32; Name = new char[MaxLength + 1]; Name[0] = '\0'; NumOfLegs = -1; } Animal(const char _N[], const int _L) { MaxLength = strlen(_N); Name = new char[MaxLength + 1]; strcpy(Name, _N); NumOfLegs = _L; } Animal(const Animal& _Ani) { MaxLength = strlen(_Ani.Name); Name = new char[MaxLength + 1]; strcpy(Name, _Ani.Name); NumOfLegs = _Ani.NumOfLegs; } ~Animal() { delete[] Name; } friend istream& operator>>(istream& in, Animal& a) { string temp; getline(in, temp); if (temp.size() > a.MaxLength) { temp = temp.substr(0, a.MaxLength); } delete[] a.Name; a.MaxLength = temp.size(); a.Name = new char[a.MaxLength + 1]; strcpy(a.Name, temp.c_str()); in >> a.NumOfLegs; in.ignore(); return in; } friend ostream& operator<<(ostream& out, const Animal& a) { out << "name is " << a.Name << ", number of legs is " << a.NumOfLegs; return out; } friend bool operator==(const Animal& a1, const Animal& a2) { return (strcmp(a1.Name, a2.Name) == 0 && a1.NumOfLegs == a2.NumOfLegs); } }; int main() { Animal FirstAnimal("Dog", 4), SecondAnimal; cout << "Please input name and number of legs of an animal:" << endl; cin >> SecondAnimal; Animal ThirdAnimal = SecondAnimal; cout << "The name and number of legs of the first animal are:" << endl; cout << FirstAnimal << endl; cout << "The name and number of legs of the second animal are:" << endl; cout << SecondAnimal << endl; cout << "The name and number of legs of the third animal are:" << endl; cout << ThirdAnimal << endl; if (FirstAnimal == ThirdAnimal) { cout << "They are equal!" << endl; } else { cout << "They are not equal!" << endl; } return 0; } ``` ## 這也是很麻煩的一題 一部車子有型號model(可包含空格的字串)與馬力horsepower(整數)兩種屬性,另外可以藉由按下喇叭發出”BiBi!”的聲音,也可藉由踩下剎車讓該車輛停止前進。 (1) 請以class設計一個名為Car的data type代表車輛,其型號與馬力兩種屬性做為其member variable(data type分別是string與int)。 (2) 請為Car這個class加入一default constructor,當中將model設為空字串,horsepower設為-1。 (3) 另有一constructor有兩個參數,兩個參數分別是data type為string的model_name跟data type為int的model_horsepower,在該constructor中,會把model跟 horsepower 的值分別設定為 model_name及 model_horsepower 的值。 (4) 該class有一個名為horn的member function,其輸出”BiBi!”字串,另一名為brake的member function則會輸出”Stop!”字串。兩者皆為void function並且沒有參數。兩者也為constant member function。 (5) 以friend function為Car重載(overload) >> 與 << 這兩個符號,分別可讓使用者輸入以及輸出一部車的型號以及馬力。 (6) 以friend function重載 == 這個符號,當中比較兩個Car變數的兩個member variable值是否相等,若都相等則回傳true,否則回傳false。 (7) 在main function中宣告兩個Car的變數,第一個變數於宣告時即有初始值”Ford Kuga”與242,第二個變數宣告時沒有初始值,接著輸入第二部車的型號以及馬力,再將兩部車的型號以及馬力輸出於螢幕中,然後比較兩部車是否相等,若相等回傳”Identical!”字串,否則回傳”Different!”字串。 ### Example Please input the model and displacement of the car: Nissan Sentra 110 The data of the two cars: The model and displacement of the car are Ford Kuga and 242. The model and displacement of the car are Nissan Sentra and 110. Different! ### ans ```cpp= // Car.h #ifndef CAR_H #define CAR_H #include <iostream> #include <string> using namespace std; class Car { public: Car(); Car(string model_name, int model_displacement); friend istream& operator >> (istream& ins, Car& _c); friend ostream& operator << (ostream& outs, const Car& _c); friend bool operator == (const Car& _c1, const Car& _c2); void horn() const; void brake() const; private: string model; int displacement; }; #endif // Car.cpp #include "Car.h" using namespace std; Car::Car() { model = ""; displacement = -1; } Car::Car(string model_name, int model_displacement) { model = model_name; displacement = model_displacement; } void Car::horn() const { cout << "BiBi!" << endl; } void Car::brake() const { cout << "Stop!" << endl; } istream& operator >> (istream& ins, Car& _c) { cout << "Input the model and displacement of the car:\n"; getline(ins, _c.model); ins >> _c.displacement; return ins; } ostream& operator << (ostream& outs, const Car& _c) { outs << "The model and displacement of the car are " << _c.model << " and " << _c.displacement << "." << endl; return outs; } bool operator == (const Car& _c1, const Car& _c2) { return ((_c1.model == _c2.model) && (_c1.displacement == _c2.displacement)); } // main.cpp #include <iostream> #include "Car.h" using namespace std; int main() { Car ACar("Ford Kuga", 242), BCar; cin >> BCar; cout << "The data of the two cars:\n"; cout << ACar << BCar; if (ACar == BCar) cout << "Identical!"; else cout << "Different!"; } ``` ## 進階題1,這題目有圖片,我懶得放 https://leetcode.com/problems/alternating-groups-iii/description/ ### ans ```cpp= #include <iostream> #include <vector> using namespace std; int altG(const vector<int>& colors, int k) { int n = colors.size(); int ans = 0; int cnt = 0; for (int i = 0; i < 2 * n; i++) { if (i > 0 && colors[i % n] == colors[(i - 1) % n]) { cnt = 1; } else { cnt++; } if (i >= n && cnt >= k) { ans++; } } return ans; } int main() { int n; cin >> n; vector<int> colors(n); for (int i = 0; i < n; i++) { cin >> colors[i]; } int k; cin >> k; cout << altG(colors, k) << endl; return 0; } ``` ## 進階題3 給定一個整數陣列 nums 和一個整數目標值 target,請你從陣列中找出和為目標值 target 的那兩個整數的索引值,並以陣列的形式回傳這兩個索引。 假設每組輸入只會有一個解,不能使用相同的元素兩次。 可以以任何順序回傳答案。 ### Example Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] ### ans ```cpp= #include <iostream> #include <vector> using namespace std; int main() { vector<int> a; int x, t; while (cin >> x) { a.push_back(x); if (cin.peek() == '\n') break; } cin >> t; for (int i = 0; i < a.size(); ++i) { for (int j = i + 1; j < a.size(); ++j) { if (a[i] + a[j] == t) { cout << i << " " << j << endl; return 0; } } } return 0; } ``` # 期中考 ## 第一題 請撰寫一支程式,其中有一int pointer變數ptr,另有一變數size。讓使用者輸入size的值後,然後將變數ptr初始化成為大小為size的dynamic array,接著讓使用者輸入ptr這個array的每個element的值,然後算出這些值的平均數後輸出至螢幕上。(20分) ### ans ```cpp= #include <iostream> using namespace std; int main() { int size; int* ptr; cout << "Please input the size of the array:" << endl; cin >> size; ptr = new int[size]; cout << "Please input " << size << " integers:" << endl; for (int i = 0; i < size; i++) { cin >> ptr[i]; } int sum = 0; for (int i = 0; i < size; i++) { sum += ptr[i]; } double avg; if (size > 0) { avg = static_cast<double>(sum) / size; } else { avg = 0; } cout << "The average is " << avg << endl; delete[] ptr; return 0; } ``` ## 第二題 2. 請撰寫一支程式,當中有一vector 變數為str,而str 所儲存的資料形別為string,接著main function中從檔案infile.txt讀入未知個數的的字串(字串可包含空格),一一以str來儲存。然後呼叫convert這個function來處理每個字串的每個符號。將大寫字母換成小寫字母、小寫字母換成大寫字母,若不為英文字母則不變。最後在main function中將處理過後的字串依序輸出至檔案outfile.txt中。請檢查開啟檔案是否失敗。(30分) ### infile.txt內容: sdaf@ 890 asd alkj90809sadfLKJsdfa outfile.txt內容: SDAF@ 890 ASD ALKJ90809SADFlkjSDFA ### ans ```cpp= #include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; string convert(const string& s) { string result = s; for (int i = 0; i < result.size(); i++) { if (isupper(result[i])) { result[i] = tolower(result[i]); } else if (islower(result[i])) { result[i] = toupper(result[i]); } } return result; } int main() { vector<string> str; ifstream infile("infile.txt"); ofstream outfile("outfile.txt"); if (!infile) { cout << "err infile" << endl; return 1; } if (!outfile) { cout << "err outfile" << endl; return 1; } string line; while (getline(infile, line)) { str.push_back(line); } for (int i = 0; i < str.size(); i++) { outfile << convert(str[i]) << endl; } infile.close(); outfile.close(); return 0; } ``` ## 第三題 請撰寫一支程式,在程式中先詢問使用接下來要輸入幾個字串,接著再讓使用者輸入這麼多個字串。程式中請以dynamic array儲存字串。每個字串皆可允許空格。接著檢視每個字串,若某個字串中含有"teacher"這個字,就刪除"teacher",若某個字串含有"student"這個字,就在其後加入" good "(good前有一空格),最後再輸出每個字串於螢幕上。(假設一個字串中最多只會出現一次"teacher"與一次"student")。(30分) ### Example How many strings do you want to input? 4 Please input strings: I like to play basketball. She is a teacher at this school. He is a student at this school. Bob is a teacher and a student at this school simultaneously. The processed strings are: I like to play basketball. She is a at this school. He is a student good at this school. Bob is a and a student good at this school simultaneously. ### ans ```cpp= #include <iostream> #include <string> using namespace std; int main() { int n; cout << "How many strings do you want to input?" << endl; cin >> n; cin.ignore(); string* lines = new string[n]; cout << "Please input strings:" << endl; for (int i = 0; i < n; i++) { getline(cin, lines[i]); } for (int i = 0; i < n; i++) { auto posTeacher = lines[i].find("teacher"); if (posTeacher != string::npos) { lines[i].erase(posTeacher, 7); } auto posStudent = lines[i].find("student"); if (posStudent != string::npos) { lines[i].insert(posStudent + 7, " good"); } while (lines[i].find(" ") != string::npos) { lines[i].erase(lines[i].find(" "), 1); } } cout << "The processed strings are:" << endl; for (int i = 0; i < n; i++) { cout << lines[i] << endl; } delete[] lines; return 0; } ``` ## 第四題 請撰寫一支程式讀取一個名稱text.txt的檔案內容。text.txt當中為一篇文章,含有若干行字串(如下例,讀取前未知行數)。在讀入文章後,該程式將判定該文章內容是屬於science類別或是sport類別。其判斷方式是根據底下各關鍵字出現的次數而定。屬於science類別的關鍵字為dinosaur與moon,屬於sport類別的關鍵字為baseball與basketball。關鍵字皆小寫。該程式會一一計算每個關鍵字在文章中的出現次數,若某個類別其兩個關鍵字的出現次數總和高於另一類別的兩關鍵字的出現次數總和,則該篇文章屬於該類別。例如text.txt內容如下。該文章中dinosaur出現2次、moon出現2次、baseball出現1次、basketball出現2次。故會被判定為science類別的文章。將在螢幕輸出"The article is a science article."。若兩類別同票數,則輸出"The article is a science and sport article."。(提示:使用vector來儲存字串,使用find()來尋找關鍵字。在一個句子中找到某關鍵字後,繼續在發現處之後尋找該關鍵字直到找不到該關鍵字為止。)(20分) text.txt: I like to play basketball. Playing baseball is also wonderful! However, he does not like to play basketball. He likes to raise a dinosaur or go to the moon; raising a dinosaur on the moon is even better! His dreams may come true in the future. Until that day, he may need a huge loan or funds to realize his dreams! ### ans ```cpp= #include <iostream> #include <fstream> #include <vector> #include <string> #include <cstdlib> using namespace std; int countKeyword(const string& line, const string& keyword) { int count = 0; int pos = line.find(keyword); while (pos != string::npos) { count++; pos = line.find(keyword, pos + keyword.length()); } return count; } int main() { ifstream fin; fin.open("text.txt"); if (fin.fail()) { cout << "open error" << endl; exit(1); } vector<string> lines; string line; while (getline(fin, line)) { lines.push_back(line); } fin.close(); int d_num = 0; int m_num = 0; int c_num = 0; int l_num = 0; for (int i = 0; i < lines.size(); i++) { d_num += countKeyword(lines[i], "dinosaur"); m_num += countKeyword(lines[i], "moon"); c_num += countKeyword(lines[i], "baseball"); l_num += countKeyword(lines[i], "basketball"); } int scienceCount = d_num + m_num; int sportCount = c_num + l_num; if (scienceCount > sportCount) { cout << "The article is a science article." << endl; } else if (sportCount > scienceCount) { cout << "The article is a sport article." << endl; } else { cout << "The article is a science and sport article." << endl; } return 0; } ``` # 期末考 ## 我沒有期末考題目 ### 抱歉,他沒給,但很簡單的,另外恭喜你們要升大二了 # 一些不重要的事情ლ(╹◡╹ლ) 嗨,各位大一的同學早安、午安、晚安 這份是因為之前有好心人寫過112年度的考古,所以我才打算整理的 如果對於這份中的程式或其他程式有任何問題可以私訊我,(另外我在找有打資安或有興趣的朋友) 特別感謝我的朋友洪于媗、吳偲瑜以及陳佳妤三位大好人幫我檢查 另外,希望到時候有能力的人,能夠幫助你們的下一屆 信箱:411335035@gms.ndhu.edu.tw Instagram: [shihyukai1211_z](https://www.instagram.com/shihyukai1211_z/)