C++ Program - Find Roots of a Quadratic Equation


Advertisements

A standard form of a quadratic quation is:

$$ax^2 + bx + c = 0$$

Where:

$$a, b$$ and $$c$$ are real numbers and $$a \ne 0$$.

Roots of the equation are:

$$\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$

For Example:

The roots of equation $$x^2 + 5x + 4 = 0$$ is

$$\frac{-5 \pm \sqrt{5^2 - 4\times1\times4}}{2\times1}$$ = $$\frac{-5 \pm \sqrt{9}}{2}$$ = $$\frac{-5 \pm 3}{2}$$ = $$-4, -1$$

The roots of the equation will be imaginari if $$D = b^2 - 4ac \lt 0$$. For example - the roots of equation $$x^2 + 4x + 5 = 0$$ will be

$$\frac{-4 \pm \sqrt{4^2 - 4\times1\times5}}{2\times1}$$ = $$\frac{-4 \pm \sqrt{-4}}{2}$$ = $$\frac{-4 \pm 2i}{2}$$ = $$-2 \pm i$$


Example: Calculate roots of a Quadratic equation

In the below example, a function called roots is created which takes $$a$$, $$b$$ and $$c$$ as arguemts to calculate the roots of the equation $$ax^2 + bx + c = 0$$.

#include <iostream>
#include <cmath>
using namespace std;

static void roots(double, double, double);

static void roots(double a, double b, double c) {
  double D = b*b - 4*a*c;
  if (D >= 0){
    double x1 = (-b + sqrt(D))/(2*a);
    double x2 = (-b - sqrt(D))/(2*a);
    cout<<"Roots of the equation ax^2 + bx + c = 0 are :\n";
    cout<<x1<<" and "<<x2<<"\n";
    cout<<"Where a, b, c are "<<a<<", "<<b<<" and "<<c<<" respectively.\n";     
  } else {
    double x1 = -b/(2*a);
    double x2 = sqrt(-D)/(2*a);
    cout<<"Roots of the equation ax^2 + bx + c = 0 are imaginary.\n";
    cout<<"Real part of root: "<<x1<<"\n";
    cout<<"Imaginary part of root: "<<x2<<"\n";
    cout<<"Where a, b, c are "<<a<<", "<<b<<" and "<<c<<" respectively.\n"; 
  }
}

int main() {
  roots(1,5,4);
  cout<<"\n";
  roots(1,4,5);
  return 0;
}

Output

Roots of the equation ax^2 + bx + c = 0 are :
-1 and -4
Where a, b, c are 1 , 5 and 4 respectively.

Roots of the equation ax^2 + bx + c = 0 are imaginary.
Real part of root: -2
Imaginary part of root: -1
Where a, b, c are 1 , 4 and 5 respectively.



Recommended Pages


Advertisements