ahmed0saber

Find roots of a quadratic equation in C++

Nov 13th, 2020
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. int main()
  5. {
  6.     float a,b,c,x1,x2,discriminant,realPart,imaginaryPart;
  7.     cout<<"Enter coefficients a, b and c : ";
  8.     cin>>a>>b>>c;
  9.     discriminant=b*b-4*a*c;
  10.     if (discriminant>0)
  11.     {
  12.         x1=(-b+sqrt(discriminant))/(2*a);
  13.         x2=(-b-sqrt(discriminant))/(2*a);
  14.         cout<<"Roots are real and different."<<endl;
  15.         cout<<"x1 = "<<x1<<endl;
  16.         cout<<"x2 = "<<x2<<endl;
  17.     }
  18.     else if (discriminant==0)
  19.     {
  20.         cout<<"Roots are real and same."<<endl;
  21.         x1=-b/(2*a);
  22.         cout<<"x1 = x2 ="<<x1<<endl;
  23.     }
  24.     else
  25.     {
  26.         realPart=-b/(2*a);
  27.         imaginaryPart=sqrt(-discriminant)/(2*a);
  28.         cout<<"Roots are complex and different."<<endl;
  29.         cout<<"x1 = "<<realPart<<"+"<<imaginaryPart<<"i"<<endl;
  30.         cout<<"x2 = "<<realPart<<"-"<<imaginaryPart<<"i"<<endl;
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment