Quadratic Equation Solution Using C++ Language

Quadratic Equation :  It is a Second degree polynomial equation. It is of the following form.

ax2 + bx +c =0

where       a , b , c    ==>   constants
                 x              ==>   unknown

If put the value of constant a  equal to zero in above equation then it becomes a linear equation. Now question is how can we solve this equation. As the degree of above polynomial equation is 2 so there are two solutions.These solution can be find out by this

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

Just put the values of constant and get two roots of solution.

Now i am going to solve the solution of above equation using C++ language.The user will enter the values of constant, and program code will solve the equation according to values of constants entered by the user.


So there are three float variables for the user to enter the values for the constants and also another two float variables for the two roots of solution.

float  a , b , c , x1 , x2 ;

In order to solve the square root , i need to include library file as given below , this library file contains pre-defined math functions.

#include <math.h>

In case of linear equation , another variable d 

float d;

Program code:

#include <iostream> 
#include <conio.h> 
#include <math.h>
using namespace std ;
int main ( ) 
   { 
     
     float   a , b , c , d , x1 , x2  ; 
     cout << "Enter the 3 coefficients for the constants a, b, c : "  << endl ; 
     cin >> a >> b >> c ; 

     if (!a) 
     { 
       if (!b
         cout << "Both a and b cannot be 0 in ax^2 + bx + c = 0" << "\n"
       else 
       
         d = -c / b; 
         cout << "The solution of the linear equation is : " << d << endl ; 
       } 
     } 
     else 
     
       d = b * b - 4 * a *; 
       if )

       x1 =     (- sqrt ) ) / ( 2*) ;

       x2 =     (- b - sqrt ( d ) ) / ( 2 *) ; 

       cout << "The first root = "      <<  x1 << endl 
       cout << "The second root = " <<  x2 << endl 

     } 
     getch () ; 
     return; 
     
   }

Hope that you will find this helpful.

No comments:

Post a Comment

Please disable your ad blocker to support this website.

Our website relies on revenue from ads to keep providing free content.