on Leave a Comment

C++ Program to Find Roots of Quadratic Equation

This c++ program calculates the roots of quadratic equation. A quadratic equation is (ax^2 + bx + c =0), where a, b and c are coefficients. 

Roots are calculated as (-b ± sqrt(b*b - 4*a*c)) / (2*a)
Where, (b*b - 4*a*c) is known as determinant of quadratic equation.

If determinant > 0, then roots are
Root1 = (-b + sqrt(b*b - 4*a*c)) / (2*a)
Root2 = (-b - sqrt(b*b - 4*a*c)) / (2*a)

If determinant = 0, then roots are
Root1 = Root2 = -b/(2*a)

If determinant < 0, then roots are
Root1 = -b/(2*a) + i(sqrt(-d)/(2*a))
Root2 = -b/(2*a) - i(sqrt(-d)/(2*a))

C++ Program to Find Roots of Quadratic Equation

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    float a, b, c, d;
    float root1, root2, img, real;
    cout<<"Enter the coefficients of quadratic equation (ax^2+bx+c=0)\n";
    cin>>a>>b>>c;
    d = b*b - 4*a*c;
    if(d>0)
    {
        root1=(-b+sqrt(d))/(2*a);
        root2=(-b-sqrt(d))/(2*a);
        cout<<"\nRoots are real and distinct";
        cout<<"\nRoots are "<<root1<<" and "<<root2;
    }
    else if(d==0)
        {
            root1=root2=-b/(2*a);
            cout<<"\nRoots are real and equal";
            cout<<"\nRoots are "<<root1<<" and "<<root2;
        }
        else{
            real = -b/(2*a);
            img = sqrt(-d)/(2*a);
            cout<<"\nRoots are complex and imaginary";
            cout<<"\nRoots are "<<real<<"+"<<img<<"i and "<<real<<"-"<<img<<"i";
        }
    return 0;
}

OUTPUT:

Enter the coefficients of quadratic equation (ax^2+bx+c=0)
1
5
2

Roots are real and distinct
Roots are -0.438447 and -4.56155

0 comments:

Post a Comment