이차 방정식은 ax 2 형식입니다. + bx + c. 이차 방정식의 근은 다음 공식으로 제공됩니다. -

세 가지 경우가 있습니다 -
b 2 <4*a*c - 뿌리가 실제가 아닙니다. 즉, 복잡합니다.
b 2 =4*a*c - 근이 실수이고 두 근이 동일합니다.
b 2 > 4*a*c - 뿌리가 실제이고 두 뿌리가 다릅니다.
이차방정식의 근을 구하는 프로그램은 다음과 같다.
예시
#include<iostream>
#include<cmath>
using namespace std;
int main() {
int a = 1, b = 2, c = 1;
float discriminant, realPart, imaginaryPart, x1, x2;
if (a == 0) {
cout << "This is not a quadratic equation";
}else {
discriminant = b*b - 4*a*c;
if (discriminant > 0) {
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "Root 1 = " << x1 << endl;
cout << "Root 2 = " << x2 << endl;
} else if (discriminant == 0) {
cout << "Roots are real and same." << endl;
x1 = (-b + sqrt(discriminant)) / (2*a);
cout << "Root 1 = Root 2 =" << x1 << endl;
}else {
realPart = (float) -b/(2*a);
imaginaryPart =sqrt(-discriminant)/(2*a);
cout << "Roots are complex and different." << endl;
cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" <<end;
cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" <<end;
}
}
return 0;
} 출력
Roots are real and same. Root 1 = Root 2 =-1
위의 프로그램에서 먼저 판별식을 계산합니다. 0보다 크면 두 근이 모두 실수이고 서로 다릅니다.
다음 코드 스니펫에서 이를 확인할 수 있습니다.
if (discriminant > 0) {
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "Root 1 = " << x1 << endl;
cout << "Root 2 = " << x2 << endl;
} 판별식이 0이면 두 근이 모두 실수이고 동일합니다. 다음 코드 스니펫에서 이를 확인할 수 있습니다.
else if (discriminant == 0) {
cout << "Roots are real and same." << endl;
x1 = (-b + sqrt(discriminant)) / (2*a);
cout << "Root 1 = Root 2 =" << x1 << endl;
} 판별식이 0보다 작으면 두 근이 모두 복소수이고 서로 다릅니다. 다음 코드 스니펫에서 이를 확인할 수 있습니다.
else {
realPart = (float) -b/(2*a);
imaginaryPart =sqrt(-discriminant)/(2*a);
cout << "Roots are complex and different." << endl;
cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" << endl;
cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" << endl;
}