C++ Program to Find All Square Roots of a Quadratic Equation

  • Write a C++ program to find the roots of a quadratic equation.

Any quadratic equation can be represented as ax2 + bx + c = 0, where a, b and c are constants( a can't be 0) and x is unknown variable.
For Example
2x2 + 5x + 3 = 0 is a quadratic equation where a, b and c are 2, 5 and 3 respectively.

To calculate the roots of quadratic equation we can use below formula. There are two solutions of a quadratic equation.
x = (-2a + sqrt(D))/2
x = (-2a - sqrt(D))/2
where, D is Discriminant, which differentiate the nature of the roots of quadratic equation.


C++ Program to find all square roots of a quadratic equation

#include <iostream>
#include <cmath> 

using namespace std;

int main() {
  float a, b, c, determinant, root1, root2, real, imag;
  cout << "Enter coefficients a, b and c of quadratic equation ax^2 + bx + c = 0 \n";
  cin >> a >> b >> c;
   
  /* Calculate determinant */
  determinant = b*b - 4*a*c;
   
  if(determinant >= 0) {
      root1= (-b + sqrt(determinant))/(2 * a);
      root2= (-b - sqrt(determinant))/(2 * a);
      cout << "Square roots are " << root1 << "  " << root2; 
  } else {
    real= -b/(2*a);
    imag = sqrt(-determinant)/(2 * a);
    cout << "Square roots are " << real << "+" << imag << "i , " << real << "-" << imag << "i";
  }
   
  return 0;
}
Output
Enter coefficients a, b and c of quadratic equation ax^2 + bx + c = 0
3 7 2
Roots of 3.00x^2 + 7.00x + 2.00 = 0 are
-0.33 and -2.00