C++ Program to Find All Roots of a Quadratic Equation
Here’s a Turbo C++ program to find all the roots of a quadratic equation:
#include <iostream.h>
#include <conio.h>
#include <math.h>
void main() {
clrscr(); // Clear the screen (specific to Turbo C++)
float a, b, c;
float discriminant, root1, root2;
cout << "Enter coefficients a, b, and c: ";
cin >> a >> b >> c;
// Calculate the discriminant
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
// Two real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
cout << "Two real and distinct roots: " << root1 << ", " << root2 << endl;
} else if (discriminant == 0) {
// Two real and equal roots
root1 = -b / (2 * a);
cout << "Two real and equal roots: " << root1 << endl;
} else {
// Two complex roots
float realPart = -b / (2 * a);
float imaginaryPart = sqrt(-discriminant) / (2 * a);
cout << "Two complex roots: " << realPart << " + " << imaginaryPart << "i, "
<< realPart << " - " << imaginaryPart << "i" << endl;
}
getch(); // Wait for user input (specific to Turbo C++)
}
To compile and run this program in Turbo C++:
- Open Turbo C++.
- Create a new file and copy-paste the above code into it.
- Save the file.
- Compile the code (usually by pressing Alt + F9).
- Run the program (usually by pressing Ctrl + F9).
The program will prompt you to enter the coefficients ( a ), ( b ), and ( c ), and then it will display the roots based on the discriminant.
