Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình C++ tìm tất cả nghiệm của phương trình bậc hai


Phương trình bậc hai có dạng ax2 + bx + c = 0. Nghiệm của phương trình được cho bởi công thức:

Chương trình C++ tìm tất cả nghiệm của phương trình bậc hai

Có ba trường hợp:

  • b2 < 4ac - Nghiệm không thực (nghiệm phức)
  • b2 = 4ac - Nghiệm thực và hai nghiệm bằng nhau
  • b2 > 4ac - Nghiệm thực và hai nghiệm khác nhau

Chương trình tìm nghiệm phương trình bậc hai:

Ví dụ

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

Đầu ra

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

Trong chương trình, trước tiên tính biệt thức (discriminant). Nếu lớn hơn 0, hai nghiệm thực khác nhau.

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

Nếu biệt thức bằng 0, hai nghiệm thực bằng nhau.

else if (discriminant == 0) {
    cout << "Roots are real and same." << endl;
    x1 = (-b + sqrt(discriminant)) / (2 * a);
    cout << "Root 1 = Root 2 = " << x1 << endl;
}

Nếu biệt thức nhỏ hơn 0, hai nghiệm phức khác nhau.

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