Program to find roots of quadratic equation in c++

Write a c++ program to find roots of quadratic equation in c++ using class.

We will find the roots of the quadratic equation using the discriminant. Suppose a quadratic equation

ax^2+bx+c=0

The discriminant D of the above equation is

D = b^2 - 4ac

The value of determinant defines the nature of the roots.

  1. If the discriminant is greater than 0, then roots are real and different. The roots x_1 and x_2 of the quadratic equation are given by
    x_1 = \dfrac{-b+\sqrt{D}}{2a} \;and\; x_2 = \dfrac{-b-\sqrt{D}}{2a}
  2. If the discriminant is equal to 0, then the roots are real and equal. The roots x of the quadratic equation are given by
    x = \dfrac{-b}{2a}
  3. If the discriminant is less than 0, then the roots are complex and different. The roots x_1 and x_2 of the quadratic equation are given by
    x_1 = \dfrac{-b+i\sqrt{|D|}}{2a} \;and\; x_2 = \dfrac{-b-i\sqrt{|D|}}{2a}

We will implement the program by creating a class QuadraticEquation.

Data Members

  1. a: Coefficient of x^2
  2. b: Coefficient of x
  3. c: Constant

Member Function

  1. Roots: Function to display roots of the quadratic equation.
#include <iostream>
#include <cmath>
using namespace std;

class QuadraticEquation {

	float a, b, c;
public:

	QuadraticEquation() {

		cout << "ax^2 + bx + c = 0" << endl;
		cout << "Enter a: ";
		cin >> a;
		cout << "Enter b: ";
		cin >> b;
		cout << "Enter c: ";
		cin >> c;

	}

	void Roots() {

		float discriminant = b * b - 4 * a * c, real, imaginary, x1, x2;

		if (a == 0) {

			cout << "Roots" << endl;
			cout << "x = " << -c << endl;

		}
		else if (discriminant > 0) {

			x1 = (-b + sqrt(discriminant)) / (2 * a);
			x2 = (-b - sqrt(discriminant)) / (2 * a);
			cout << "Roots are real and different" << endl;
			cout << "x1 = " << x1 << endl;
			cout << "x2 = " << x2 << endl;

		}
		else if (discriminant == 0) {

			cout << "Roots are real and equal" << endl;
			x1 = (-b + sqrt(discriminant)) / (2 * a);
			cout << "x =" << x1 << endl;

		}
		else {

			real = -b / (2 * a);
			imaginary = sqrt(-discriminant) / (2 * a);
			cout << "Roots are complex and different." << endl;
			cout << "x1 = " << real << "+" << "i" << imaginary << endl;
			cout << "x2 = " << real << "-" << "i" << imaginary << endl;

		}

	}

};


int main() {

	QuadraticEquation qe;
	qe.Roots();

}

Output

c++ program to find roots of a quadratic equation using classes

Read
Program to Print Diamond Pattern (using both loop and recursion)
Program to multiply matrices using recursion

Leave a Comment

Your email address will not be published.