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:
- Input the coefficients of the quadratic equation
- Determine the determinant of the coefficients
- Check whether $a$ is $0$ or not
- If $a \ne 0$ then check determinant
- If $determinant \gt 0$ roots are real and different
- If $determinant = 0$ roots are real and same
- Otherwise roots are complex
- Find the roots based on above criteria
- 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