Quadratic equation C++ program to find roots using if else

This is a simple C++ program to find roots of quadratic equation using if else. I have given the variable names according to the need. Here x, y & z are the coefficients of the a quadratic equation xa2+ya+z = 0. The formula to find the roots is shown in the Image below.

This is a simple C++ program to find roots of quadratic equation using if else. I have given the variable names according to the need. Here x, y & z are the coefficients of the a quadratic equation xa2+ya+z = 0. The formula to find the roots is shown in the Image below.

The roots of the equation is given by Root1 and Root2 variables. We used cmath library to use some mathematical functions like sqrt(). This is very simple C++ program to understand and compile. I have used nested if else in this program.

#include <iostream>
#include <cmath>
using namespace std;
int main() {
float x, y, z, Root1, Root2, determinant, real, imaginary; //declare the variables
cout << "Enter coefficients x, y and z: ";
cin >> x >> y >> z;   //enter the coefficients
determinant = y*y - 4*x*z; //formula for determinants
if (determinant > 0) {
Root1 = (-y + sqrt(determinant)) / (2*x); //sqrt() is for finding square root
Root2 = (-y - sqrt(determinant)) / (2*x);
cout << "Nature of Roots: Real and different." << endl;
cout << "Root1 = " << Root1 << endl;
cout << "Root2 = " << Root2 << endl;
}
else if (determinant == 0) {
cout << "Nature of Roots: Real and same." << endl;
Root1 = (-y + sqrt(determinant)) / (2*x);
cout << "Root1 = Root2 =" << Root1 << endl;
}
else {
real = -y/(2*x);
imaginary =sqrt(-determinant)/(2*x);
cout << "Nature of Roots: Complex and different."  << endl;
cout << "Root1 = " << real << "+" << imaginary << "i" << endl;
cout << "Root2 = " << real << "-" << imaginary << "i" << endl;
}
return 0;
}

Output of this program:
As an example if I take a equation 2a^2+3a+1=0 then the output will be as shown below.

So try this C++ program to find roots of quadratic equation using if else on your compiler. You can use Dev C++ or Codeblock compiler to compile this program. You can also use Best online compilers and IDE to run and test your codes or program online. Thank you for reading

Name

ltr
item
MindxMaster: Quadratic equation C++ program to find roots using if else
Quadratic equation C++ program to find roots using if else
This is a simple C++ program to find roots of quadratic equation using if else. I have given the variable names according to the need. Here x, y & z are the coefficients of the a quadratic equation xa2+ya+z = 0. The formula to find the roots is shown in the Image below.