Finding Roots of a Quadratic Equation in C++

Exercise:

Write a C++ Program to calculate the roots of a quadratic equation with the coefficients provided by the user.

Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    float a, b, c, x1, y1, disc, R, Img;
    cout << "Enter coefficients a, b and c:\n";
    cin >> a >> b >> c;
    disc = pow(b,2) - 4*a*c;
    if (disc > 0)
    {
        x1 = ((-b + sqrt(disc)) / (2*a));
        y1 = ((-b - sqrt(disc)) / (2*a));
        cout << "Roots are Real and different " << endl;
        cout << "x1 = " << x1 << endl;
        cout << "y1 = " << y1 << endl;
    }
     else if (disc == 0) 
    {
        cout << "Roots are Real and equal " << endl;
        x1 = -b/(2*a);
        cout << "x1 = y1 =" << x1 << endl;
    }
     else
    {
        R = -b/(2*a);
        Img =sqrt(-disc)/(2*a);
        cout << "Roots are Complex and different "  << endl;
        cout << "x1 = " << R << "+" << Img << "i" << endl;
        cout << "y1 = " << R << "-" << Img << "i" << endl;
    }
     return 0;
 }

Click Here to View the Output:
Enter coefficients a, b and c:
2
3
4
Roots are Complex and different
x1 = -0.75+1.19896i
y1 = -0.75-1.19896i
Click Here to View the Explanation:
  • The quadratic equation: ax2+bx+c = 0 is used to find the roots of the provided coefficients (a, b and c). The following formula is derived by subjecting x from the quadratic equation, giving negative and positive roots.
BioMath: Quadratic Functions
  • In this quadratic equation, the discriminant of this equation is: b2-4ac. This can provide some information about the expected roots of the equation.
  • A positive discriminant indicates different and real roots.
  • When disc == 0, it indicates equal and real roots.
  • A negative discriminant indicates different and complex roots.
  • The square root for this solution is found using the function: sqrt() from the <cmath> library.
  • The result is displayed on the screen.

%d bloggers like this: