# a006. 一元二次方程式 ## C語言 ### 觀念: 1. double sqrt(double x) 在<math.h>, 要特別注意是浮點數型態 [2] 2. 型別轉換: - 將int32轉換為double=> 新增小數部分 - 將double轉換為int=> 小數部分會遺失 - 將(double)a+(int)b=> 因為其中一個是double, 將會導致b被轉換為double -(int)c=(double)a+(int)b =>小數部分會遺失 更詳細可參考[4] 3. 一開始將 ```(-b + sqrt(b * b - 4 * a * c)) / (2 * a)``` 寫成 ```(-b + sqrt(b * b - 4 * a * c)) / 2 * a``` 導致NA ### AC程式碼: ``` #include<stdio.h> #include<stdlib.h> #include<math.h> main(){ int a = 0, b = 0, c = 0, x1 = 0, x2 = 0, i = 0; scanf("%d %d %d", &a, &b, &c); x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a); //double sqrt(double x) x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a); if(sqrt(b * b - 4 * a * c) * sqrt(b * b - 4 * a * c) != b * b - 4 * a * c){ printf("No real root\n"); //break; } else{ if(x1 == x2){ printf("Two same roots x=%d\n", x1); } else{ printf("Two different roots x1=%d , x2=%d\n", x1, x2); } } return 0; } ``` ## Reference: [1] 題目來源:[高中生程式解題系統](https://zerojudge.tw/ShowProblem?problemid=a006) [2] [C Programming/math.h/sqrt](https://en.wikibooks.org/wiki/C_Programming/math.h/sqrt) [3] [ChatGPT](https://chat.openai.com) [4] [深入理解計算機系統, 3/e(CSAPP中文版)](https://www.tenlong.com.tw/products/9787111544937)