Pages

Thursday 17 December 2015

Roots of quadratic equations using C++


Quadratic Equation:
A quadratic equation is any equation in any form $ax^2 + bx + c = 0$, where $a \ne 0$. Finding the roots of the quadratic equation is nothing but solving the equation for $x$. Any quadratic equation can be solved by the formula :

$x = \frac{-b \pm {\sqrt {b^2 - 4ac}}}{2a}$

Algorithm:
  1. Input the coefficients of the quadratic equation
  2. Determine the determinant of the coefficients
  3. Check whether $a$ is $0$ or not 
  4. If $a \ne 0$ then check determinant
  5. If $determinant \gt 0$ roots are real and different
  6. If $determinant = 0$ roots are real and same
  7. Otherwise roots are complex
  8. Find the roots based on above criteria
  9. Stop the program

#include "iostream"
#include "conio.h"
#include "math.h"

using namespace std;

int main()
{
    float a,b,c,x,y, determinant, real, imaginary;

    cout << "Enter coefficients a, b and c : " ;
    cin >> a >> b >> c ;
    determinant = b*b - 4*a*c;

    if(a==0)
    {
        cout << " 'a' can not be zero" ;
    }
    else
    {
        if(determinant > 0)
        {
            x= (-b + sqrt(determinant))/(2*a);
            y= (-b - sqrt(determinant))/(2*a);
            cout <<"Roots are real and different:" <<endl;
            cout << "x :" << x << endl;
            cout << "y :" << y << endl;
        }
        else if (determinant == 0)
        {
            cout << "Roots are real and same " << endl;
            x = (-b + sqrt(determinant))/(2*a);
            cout << "x = y =" << x << endl;
        }
        else
        {
          real = -b/(2*a);
          imaginary = sqrt(-determinant)/(2*a);
          cout << "x = " << real << "+" << imaginary << "i" << endl;
          cout << "y = " << real << "-" << imaginary << "i" << endl;
        }
        return (0);
    }
}



INPUT :     Enter coefficients a, b and c : 4 5 6
OUTPUT : x = -0.625+1.05327i
                    y = -0.625-1.05327i


No comments:

Post a Comment