C++ Online Compiler
Example: C++ Program to Find the Roots of a Quadratic Equation using sqrt() Function
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// 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; }
6.6 5.5 4
Output
Clear
ADVERTISEMENTS