Write a C++ Program to Find All Roots of a Quadratic Equation

A quadratic equation is an equation of the form ax^2 + bx + c = 0, where a, b, and c are constants and x is the variable.

The roots of a quadratic equation are the values of x that satisfy the equation.

In this tutorial, we will discuss how to find all roots of a quadratic equation in C++.

There are several methods to find the roots of a quadratic equation, but we will use the formula:

x = (-b ± sqrt(b^2 – 4ac)) / 2a

This formula is derived from the quadratic equation by completing the square.

It is called the quadratic formula, and it can be used to find the roots of any quadratic equation.

To implement this formula in C++, we can use the following code:

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double a, b, c, root1, root2;

    cout << "Enter coefficients a, b and c: ";
    cin >> a >> b >> c;

    // Calculate the discriminant
    double discriminant = b * b - 4 * a * c;

    // If discriminant is positive
    if (discriminant > 0)
    {
        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;
    }

    // If discriminant is zero
    else if (discriminant == 0)
    {
        root1 = root2 = -b / (2 * a);
        cout << "Roots are real and same." << endl;
        cout << "Root 1 = Root 2 = " << root1 << endl;
    }

    // If discriminant is negative
    else
    {
        double realPart = -b / (2 * a);
        double 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;
}

In this code, we first declare the variables a, b, c, root1, and root2 as doubles. We then prompt the user to enter the values of a, b, and c using the cout and cin statements.

We calculate the discriminant using the formula b * b – 4 * a * c.

Next, we use an if-else statement to determine the nature of the roots. If the discriminant is positive, the roots are real and different, and we calculate them using the quadratic formula.

If the discriminant is zero, the roots are real and same, and we calculate them by using the formula root1 = root2 = -b / (2 * a).

If the discriminant is negative, the roots are complex and different, and we calculate them using the formula realPart = -b / (2 * a) and imaginaryPart = sqrt(-discriminant) / (2 * a).

Finally, we use the cout statement to display the roots to the user.

In conclusion, we have discussed how to find all roots of a quadratic equation in C++.