Press ESC to close

How To Find All Roots of a Quadratic Equation in C++

Photo by Nemuel Sereti

Straightforward C++ program to find all the roots of a quadratic equation:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    double a, b, c;
    double root1, root2, discriminant, realPart, imaginaryPart;
    // Get coefficients a, b, and c from the user
    cout << "Enter coefficients a, b, and c: ";
    cin >> a >> b >> c;
    // Calculate the discriminant
    discriminant = b * b - 4 * a * c;
    // Check the nature of the roots using the discriminant
    if (discriminant > 0) {
        // Two distinct real roots
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        cout << "Roots are real and different." << endl;
        cout << "Root 1 = " << root1 << endl;
        cout << "Root 2 = " << root2 << endl;
    } else if (discriminant == 0) {
        // Two equal real roots
        root1 = root2 = -b / (2 * a);
        cout << "Roots are real and the same." << endl;
        cout << "Root 1 = Root 2 = " << root1 << endl;
    } else {
        // Complex roots
        realPart = -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;
}

Explanation:

  1. We include the necessary headers: iostream for input/output and cmath for mathematical functions.
  2. We declare variables to store the coefficients aaa, bbb, and ccc, the roots, and parts of the roots.
  3. We prompt the user to enter the coefficients of the quadratic equation.
  4. We calculate the discriminant (b2−4acb^2 – 4acb2−4ac).
  5. We check the value of the discriminant to determine the nature of the roots:
    • If the discriminant is greater than zero, the equation has two distinct real roots.
    • If the discriminant is zero, the equation has two equal real roots.
    • If the discriminant is less than zero, the equation has two complex roots.
  6. We print the roots based on the above conditions.

Leave a Reply

Your email address will not be published. Required fields are marked *