Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

이차 방정식의 모든 근을 구하는 C++ 프로그램


이차 방정식은 일반적으로 ax2 + bx + c = 0(단, a ≠ 0) 형태로 표현되며, 그 근은 다음과 같은 근의 공식을 통해 구할 수 있습니다.

x = ( −b ± √(b2 − 4ac) ) / 2a

여기서 b2 − 4ac 부분을 판별식(discriminant)이라고 합니다. 판별식의 값에 따라 근의 성질은 다음과 같이 세 가지 경우로 나뉩니다.

  • b2 < 4ac : 근은 실수가 아니며, 서로 다른 두 복소수(허수)입니다.
  • b2 = 4ac : 근은 실수이며, 두 근이 서로 같습니다(중근).
  • b2 > 4ac : 근은 실수이며, 두 근이 서로 다릅니다.

다음은 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" << endl;
            cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" << endl;
        }
    }
    return 0;
}

출력 결과

Roots are real and same.
Root 1 = Root 2 =-1

위 프로그램에서는 먼저 계수 a가 0인지 검사합니다. a가 0이면 이차 방정식이 아니므로 해당 메시지를 출력하고, a가 0이 아닐 때에만 판별식을 계산한 뒤 그 값에 따라 세 가지 경우로 분기하여 근을 출력합니다.

1. 판별식이 0보다 큰 경우 : 서로 다른 두 실근

판별식이 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;
}

2. 판별식이 0인 경우 : 중근

판별식이 정확히 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;
}

3. 판별식이 0보다 작은 경우 : 서로 다른 두 복소근

판별식이 0보다 작으면 제곱근 안의 값이 음수가 되므로 근은 실수가 아니라 복소수입니다. 이때는 실수부(realPart)와 허수부(imaginaryPart)를 나누어 계산한 후 출력합니다.

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;
}