Here we are discussing a C++ program to find all roots of a quadratic equation.
In math, we define a quadratic equation as an equation of degree 2, meaning that the highest exponent of this function is 2. The standard form of a quadratic is y = ax2 + bx + c, where a, b, and c are numbering and a cannot be 0.
Example : 6x2 + 11x – 35 = 0.
For a quadratic equation ax2 + bx + c = 0, The roots are calculated using the formula,
x = (-b ± √ (b² - 4ac) ) / 2a
Where,
With respect to the value of discriminant the roots of the equation will be
Ask the user to enter the value of three variables a, b, and c. First, calculate the value of the discriminant by using the formula, Discriminant = b² - 4ac. Store the value to variable discrim, which is of float type.
For the discriminant value, we have three conditions. as we discussed above which will be less than or equal to, or greater than zero. This can be done by using the if….else if….else
statement.
If the value of discrim is greater than zero ( discrim > 0 ) calculate the roots by the formula (-b ± √ (b² - 4ac) )/2a. In this equation, the square root will find out using the function sqrt function. The sqrt() function in C++ is used for calculating the square root. it is defined in the cmath header of C++.
Else if the discriminant value is equal to zero ( discrim = = 0 )
Else there are two parts real part and the imaginary part.
Step 1: Call the header file iostream.
Step 2: Call the header file cmath.
Step 3: Use the namespace std
Step 4: Open the main function int main().
Step 5: Declare float variables; a, b, c, R1, R2, discrim, ipart, rpart
Step 6: Print a message to enter coefficients a, b, and c;
Step 7: Read the numbers into the variables a, b, and c.
Step 8: Calculate the discriminant discrim = b2 - 4ac.
Step 9: if the discrim >0
Else if discrim = 0
Else if discrim < 0
Step 10: Exit
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float a, b, c, R1, R2, discrim, rPart, iPart;
cout << "Enter coefficients a, b and c: ";
cin >> a >> b >> c;
discrim= b*b - 4*a*c;
if (discrim> 0) {
R1 = (-b + sqrt(discrim)) / (2*a);
R2 = (-b - sqrt(discrim)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "R1 = " << R1 << endl;
cout << "R2 = " << R2 << endl;
}
else if (discrim == 0) {
cout << "Roots are real and same." << endl;
R1 = -b/(2*a);
cout << "R1 = R2 =" << R1 << endl;
}
else {
rPart = -b/(2*a);
iPart =sqrt(-discrim)/(2*a);
cout << "Roots are complex and different." << endl;
cout << "x1 = " << rPart << "+" << iPart << "i" << endl;
cout << "x2 = " << rPart << "-" << iPart << "i" << endl;
}
return 0;
}
Enter coefficients a, b and c: 5 3 6 Roots are complex and different. x1 = -0.3+1.05357i x2 = -0.3-1.05357i