題目連結 https://zerojudge.tw/ShowProblem?problemid=a006。
一元二次方程式解的公式(下圖取自 Wikipedia 一元二次方程式):
先求出一元二次方程式根的判別式(下圖取自 Wikipedia 一元二次方程式):
判斷是否有實數解,相等根。再用公式求出兩根的解即可。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cmath> | |
using namespace std; | |
int main() | |
{ | |
double a, b, c; | |
while( cin >> a >> b >> c ) | |
{ | |
int check = b * b - 4 * a * c; | |
bool noRoot = check < 0; | |
if( noRoot == true ) | |
{ | |
cout << "No real root" << endl; | |
} | |
else | |
{ | |
if( check == 0 ) | |
{ | |
int x = -b / (2 * a); | |
cout << "Two same roots x=" << x << endl; | |
} | |
else | |
{ | |
int x1 = (-b + sqrtl(check)) / (2 * a); | |
int x2 = (-b - sqrtl(check)) / (2 * a); | |
cout << "Two different roots x1=" << x1 << " , x2=" << x2 << endl; | |
} | |
} | |
} | |
return 0; | |
} |
沒有留言:
張貼留言