# HW04 參考答案 ## 4.1 System Monitor ## 4.2 How to Rent your Bike? ## 4.3 Do Challenge Compiler in This Class!! ## 4.4 Bonus: Wildcard \* 可以匹配所有字元,因此對應的是所有的 .c 檔案 ## 4.5 Bonus: Bit Operation right shift operation 會使用 1 進行補充而非 0 ,因而導致錯誤 ## 4.6 Bonus: MACRO Credit: 41247001S 盧O安 ``` 首先我先把code複製下來後跑了一次 發現他輸出了 sizeof ( plist ) / sizeof ( double ) = 1 sizeof ( list ) / sizeof ( double ) = 3 先來說說 macro define #cmd 是等於把cmd 變成字串,所以分別輸出了 sizeof ( plist ) / sizeof ( double ) 以及 sizeof ( list ) / sizeof ( double ) 是合理的 ``` ## 4.7 Bonus: tgmath.h Credit: 41247050S 郝O彥 ### 比較表格 | 特性 | `math.h` | `tgmath.h` | |------ |---------- |------------| | **函數定義方式** | 指明類型(`pow`, `powf`, `powl`) | macro自動選函數 | | **函數範例** | `double pow(double, double)`<br>`float powf(float, float)`<br>`long double powl(long double, long double)` | `pow(2.0, 3.0)` 自動選擇<br>`pow(2.0f, 3.0f)` 自動選擇<br>`pow(2.0L, 3.0L)` 自動選擇 | | **優點** | 明確數據類型 | 簡化調用,減少錯誤 | :::spoiler BONUS07.c ```c #include <stdio.h> #include <math.h> #include <tgmath.h> int main() { // 使用 math.h 的 pow 函數 double base1 = 2.0; double exponent1 = 3.0; double result_math_double = pow(base1, exponent1); printf("math.h pow(2.0, 3.0) = %f\n", result_math_double); float base2 = 2.0f; float exponent2 = 3.0f; float result_math_float = powf(base2, exponent2); printf("math.h powf(2.0f, 3.0f) = %f\n", result_math_float); long double base3 = 2.0L; long double exponent3 = 3.0L; long double result_math_long_double = powl(base3, exponent3); printf("math.h powl(2.0L, 3.0L) = %Lf\n", result_math_long_double); // 使用 tgmath.h 的 pow 函數 double result_tgmath_double = pow(base1, exponent1); printf("tgmath.h pow(2.0, 3.0) = %f\n", result_tgmath_double); float result_tgmath_float = pow(base2, exponent2); printf("tgmath.h pow(2.0f, 3.0f) = %f\n", result_tgmath_float); long double result_tgmath_long_double = pow(base3, exponent3); printf("tgmath.h pow(2.0L, 3.0L) = %Lf\n", result_tgmath_long_double); // 混合型態 double base4 = 2.0; float exponent4 = 3.0f; double result_tgmath_mixed = pow(base4, exponent4); printf("tgmath.h pow(2.0, 3.0f) = %f\n", result_tgmath_mixed); long double base5 = 2.0L; double exponent5 = 3.0; long double result_tgmath_mixed_ld = pow(base5, exponent5); printf("tgmath.h pow(2.0L, 3.0) = %Lf\n", result_tgmath_mixed_ld); return 0; } ``` :::