C++ 求二次方程的所有根程序

要理解本示例,您应该了解以下 C++ 编程 主题


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

Formula to find root of an quadratic equation
求二次方程根的公式

b2-4ac 被称为二次方程的判别式。判别式决定了根的性质。

  • 如果判别式大于 0,则根为实数且不相等。
  • 如果判别式等于 0,则根为实数且相等。
  • 如果判别式小于 0,则根为复数且不相等。
Calculation of roots of a quadratic equation
计算二次方程的根

示例:二次方程的根

#include <iostream>
#include <cmath>
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/(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() 库函数用于查找数字的平方根。

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数来查找二次方程的根。

  • 返回二次方程的根,系数为 abc
  • 求二次方程根的公式是:x = [-b ± sqrt(b^2 - 4ac)] / 2a。使用此公式计算根。
  • 例如,如果 a = 1b = -5c = 6,则返回值应为 {3, 2}
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战