Google News
logo
C++ Program to Find All Roots of a Quadratic Equation
In the following example of C++ program that finds all the roots of a quadratic equation entered by the user :
Program :
#include <iostream>
#include <cmath>

int main() {
    double a, b, c, root1, root2, realPart, imaginaryPart;
    std::cout << "Enter coefficients a, b, and c: ";
    std::cin >> a >> b >> c;
    double discriminant = b * b - 4 * a * c;
    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        std::cout << "Roots are real and different." << std::endl;
        std::cout << "Root 1 = " << root1 << std::endl;
        std::cout << "Root 2 = " << root2 << std::endl;
    }
    else if (discriminant == 0) {
        root1 = root2 = -b / (2 * a);
        std::cout << "Roots are real and same." << std::endl;
        std::cout << "Root 1 = Root 2 = " << root1 << std::endl;
    }
    else {
        realPart = -b / (2 * a);
        imaginaryPart = sqrt(-discriminant) / (2 * a);
        std::cout << "Roots are complex and different."  << std::endl;
        std::cout << "Root 1 = " << realPart << "+" << imaginaryPart << "i" << std::endl;
        std::cout << "Root 2 = " << realPart << "-" << imaginaryPart << "i" << std::endl;
    }
    return 0;
}
Output :
Enter coefficients a, b, and c: 2
5
9
Roots are complex and different.
Root 1 = -1.25+1.71391i
Root 2 = -1.25-1.71391i
* This program declares six variables : a, b, c, root1, root2, realPart, and imaginaryPart, which are all of type double.

* The program then prompts the user to enter the coefficients a, b, and c of the quadratic equation using the std::cout and std::cin objects from the iostream library.

* The >> operator is used to input the user's numbers into the variables a, b, and c.

* The program then calculates the discriminant of the quadratic equation using the formula b^2 - 4ac. The program uses conditional statements to determine the type of roots of the quadratic equation (real and different, real and same, or complex and different) based on the value of the discriminant.

* If the discriminant is greater than 0, then the roots are real and different, and the program calculates and outputs the roots. If the discriminant is equal to 0, then the roots are real and same, and the program calculates and outputs the roots.

* If the discriminant is less than 0, then the roots are complex and different, and the program calculates and outputs the roots.

* The program uses std::cout to output the type of roots and the roots (or real and imaginary parts of the roots, in the case of complex roots) to the console.