📜  用C++程序查找二次方程式的所有根

📅  最后修改于: 2020-09-25 06:30:42             🧑  作者: Mango

该程序从用户那里接受二次方程式的系数,并显示根(实数根和复数根都取决于判别式)。

对于二次方程ax 2 + bx + c = 0 (其中a,b和c为系数),其根由以下公式给出。

查找二次方程式根的公式

术语b 2 -4ac被称为二次方程的判别式。判别式说明了根的性质。

二次方程的根的计算

示例:二次方程的根

#include 
#include 
using namespace std;

int main() {

    float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
    cout << "Enter coefficients a, b and c: ";
    cin >> a >> b >> c;
    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 << "x1 = " << x1 << endl;
        cout << "x2 = " << x2 << endl;
    }
    
    else if (discriminant == 0) {
        cout << "Roots are real and same." << endl;
        x1 = (-b + sqrt(discriminant)) / (2*a);
        cout << "x1 = x2 =" << x1 << endl;
    }

    else {
        realPart = -b/(2*a);
        imaginaryPart =sqrt(-discriminant)/(2*a);
        cout << "Roots are complex and different."  << endl;
        cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
        cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
    }

    return 0;
}

输出

Enter coefficients a, b and c: 4
5
1
Roots are real and different.
x1 = -0.25
x2 = -1

在此程序中, sqrt()库函数用于查找数字的平方根。