題解: 這裡要具備的基本知識為國中一元二次方程式的判別式用法,以及要注意開根號的用法為sqrt(),了解這個之後只需要注意在寫算是時要注意()的位置以及要分正跟負=>因為公式解有兩解。
兩解分別為
C++解法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 #include <bits/stdc++.h> using namespace std;int main () { int a, b, c, d; cin >> a >> b >> c; d = b * b - 4 * a * c; int x1 = (-b + sqrt (b * b - 4 * a * c)) / (2 * a); int x2 = (-b - sqrt (b * b - 4 * a * c)) / (2 * a); if (d > 0 ) { cout << "Two different roots " ; cout << "x1=" << x1 << " ," << " x2=" << x2; } else if (d == 0 ) { cout << "Two same roots " ; int x = x1 = x2; cout << "x=" << x; } else cout << "No real root" ; }
Python解法 1 2 3 4 5 6 7 8 9 10 11 12 13 import matha,b,c=map (int ,input ().split()) d = b * b - 4 * a * c if (d > 0 ): x1 = int ((-b + math.sqrt(b * b - 4 * a * c)) // (2 * a)) x2 = int ((-b - math.sqrt(b * b - 4 * a * c)) // (2 * a)) print (f"Two different roots x1={x1} , x2={x2} " ) elif (d == 0 ): x1 = int ((-b + math.sqrt(b * b - 4 * a * c)) // (2 * a)) print (f"Two same roots x={x1} " ) else : print ("No real root" )
範例輸入 範例輸出 1 0 0 Two same roots x=0 1 3 -10 Two different roots x1=2 , x2=-5 1 1 1 No real root