> [name=106-26-王湘鈴] 程式作業 # 23題 ![IMG_2303](https://hackmd.io/_uploads/B1axQn5E1e.jpg) ## %=是什麼 ```cpp= a%=b// a=a%b ``` ## 程式碼 ```cpp= #include<iostream> #include<sstream> // 用來引入 istringstream using namespace std; int main() { string time1, time2; // 先定義字串,後面用來讀取時間 cin >> time1 >> time2; int h1, m1, s1, h2, m2, s2; char colon; // 用來忽略冒號,colon是冒號的英文 istringstream stream1(time1); stream1 >> h1 >> colon >> m1 >> colon >> s1; istringstream stream2(time2); stream2 >> h2 >> colon >> m2 >> colon >> s2; // 簡單暴力全換成秒數 int time1_seconds = h1 * 3600 + m1 * 60 + s1; int time2_seconds = h2 * 3600 + m2 * 60 + s2; if (time2_seconds < time1_seconds) { time2_seconds += 24 * 3600; } int diff_seconds = time2_seconds - time1_seconds; // 時間差(秒數) int hours = diff_seconds / 3600; diff_seconds %= 3600; int minutes = diff_seconds / 60; int seconds = diff_seconds % 60; // 輸出時間差的時數,確保格式為兩位數(如果小於10,前面補零) if (hours < 10) cout << "0"; cout << hours << ":"; if (minutes < 10) cout << "0"; cout << minutes << ":"; if (seconds < 10) cout << "0"; cout << seconds << endl; return 0; } ``` ## 為何sscanf後面要用,C-style呢? C-style 字符串 是基於字符陣列的字符串,使用 char* 或 char[] 類型,並以 \0 結尾。 C++ 字符串(std::string) 是 C++ 標準庫提供的一個更高級的字符串類型,內部處理了字符的存儲和結尾標誌。 sscanf 是 C 語言中的函數,它只能處理 C-style 字符串,所以我們必須將 C++ 字符串(std::string)轉換為 C-style 字符串(使用 .c_str())。 簡而言之,scanf只認識C-style字符串!所以我們必須吧C++字符串轉換成C-style,就要使用 .c_str() ## sscanf定義(C) ```cpp=98 int sscanf (const char *str, const char *format, ...); ``` ## +=是什麼? ```cpp= //用在整數部分 int a = 5; a += 3; // 等同於 a = a + 3; cout << a; // 輸出 8 ``` ## %d %d:代表 "整數"(decimal integer)。它告訴 sscanf 在時間字符串中查找整數,並將它們解析成變數。 ## ==跟=的差別 ```cpp= a=b//有點類似把a定義為b a==b//一種比較的感覺,就是a跟b比較起來是相等的 ``` ### 程式碼 ```cpp= #include<iostream> using namespace std; int main() { string time1, time2; //先定義字串,後面sscanf會用到 cin >> time1 >> time2; int h1, m1, s1, h2, m2, s2; char colon; // 用來忽略冒號,避免解析時遇到問題 // "HH:MM:SS" 格式 sscanf(time1.c_str(), "%d:%d:%d", &h1, &m1, &s1); sscanf(time2.c_str(), "%d:%d:%d", &h2, &m2, &s2); // 簡單暴力全換成秒數 int time1_seconds = h1 * 3600 + m1 * 60 + s1; int time2_seconds = h2 * 3600 + m2 * 60 + s2; // 後面用:時間2-時間1 if (time2_seconds < time1_seconds) { time2_seconds += 24 * 3600; } int diff_seconds = time2_seconds - time1_seconds; // 換算 int hours = diff_seconds / 3600; diff_seconds %= 3600; int minutes = diff_seconds / 60; int seconds = diff_seconds % 60; // 輸出時間差的時數,確保格式為兩位數(如果小於10,前面補零) if (hours < 10) cout << "0"; cout << hours << ":"; if (minutes < 10) cout << "0"; cout << minutes << ":"; if (seconds < 10) cout << "0"; cout << seconds << endl; return 0; } ```