New Program to Solve Quadratic equation in C++

Here we will a write a program to solve quadratic equation in C++ programming language. Let’s first understand how to solve a quadratic equation:

Let’s take the quadratic equation as: ax²+bx+c=0

How program works:

  • Take the values for a, b and c (double type).
  • if, a = b = 0 then invalid equation
  • if b² -4ac < 0 then the real roots
  • if b² -4ac > 0 , x1= (-b+√(b² -4ac))/2a , x1= (-b -√(b² -4ac))/2a
  • The C++ function for √x is sqrt(x).
  • Include math.h for using the sqrt() function.

Now let’s write the program for the same.

Here is a program to solve Quadratic equation in Python

Program to solve Quadratic equation in C++

#include<iostream>
#include<cmath>
#include<cstdlib>
#include<cstring>
using namespace std;
int main()
{
 double a,b,c,x1,x2;
 char x;
 cout<<"enter the value of a=";
 cin>>a;
 cout<<"enter the value of b=";
 cin>>b;
 cout<<"enter the value of c=";
 cin>>c;
 cout<<"the quadratic equation is"<<a;
 cout<<"*x*x+"<<b;
 cout<<"*x+"<<c<<endl;
 if
 
 (a==0 && b==0)
 cout<<"not a valid equation";
 if
 
 (a==0 && b!=0)
 {
 x1=-(c/b);
 
 
 cout<<endl;
 cout<<"root="<<x1;
 cout<<endl; 
}
 if ((b*b-4*a*c)>0)
 {
     x2=(b*b)-(4*a*c);
     x1=-b+sqrt(x2);
     cout<<"root="<<x1<<endl;
 }
 if ((b*b-4*a*c)<0)
 {
 cout<<"not a real root"<<endl;
}
 system("pause");
 return 0;
}

 

OUTPUT:

enter the value of a=15
enter the value of b=16
enter the value of c=21
the quadratic equation is15*x*x+16*x+21
not a real root

Please comment for any concern or suggestions for improvements.

1 thought on “New Program to Solve Quadratic equation in C++”

Leave a Comment