C++ Program to Find the Roots of a Quadratic Equation using sqrt() Function
ADVERTISEMENTS
C++ program to find the roots of a quadratic equation using sqrt() function. In this article, you will learn how to find the roots of a quadratic equation in c++ language using sqrt() function.
What is the Quadratic equation?
ax2 + bx + c = 0
where a, b and c these are the real numbers & a != 0
where a, b and c these are the real numbers & a != 0
Source Code
// C++ Program to Find the Roots of a Quadratic Equation using sqrt() Function
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
// `iomanip` header file loaded to print the double value with 2 precision
// `cmath` header file loaded to call the sqrt() function
int main() {
double p, q, r, d, r1, r2, rp, ip;
// p, q and r - To store the real numbers
// d - To store the discriminant
// r1 - To store the first root
// r2 - To store the second root
// rp - To store the real part
// ip - To store the image part
cout << "-----Enter these coefficients a, b and c----\n";
cin >> p >> q >> r;
d = q * q - 4 * p * r;
if (d > 0) {
// It is the condition for real and different roots
r1 = (-q + sqrt(d)) / (2 * p);
r2 = (-q - sqrt(d)) / (2 * p);
cout << "\nThe r1 = " << r1 << " & r2 = " << r2 << "\n";
} else if (d == 0) {
// It is the condition for real and equal roots
r1 = r2 = -q / (2 * p);
cout << "\nThe r1 = r2 = " << r1 << ";\n";
} else {
// if the roots are not real number
rp = -q / (2 * p);
ip = sqrt(-d) / (2 * p);
std::cout << std::fixed << std::setprecision(2) << "\nThe r1 = " << rp << "+" << ip << "i & r2 = " << rp << "-" << ip << "i\n";
}
return 0;
}
Output
-----Enter these coefficients a, b and c----
6.6
5.5
4
The r1 = -0.42+0.66i & r2 = -0.42-0.66i