C++ Program to Find Quadratic Equation Roots
Overview
In this tutorial, we will write a simple C++ Program to Find Quadratic Equation Roots. The roots for the equation can be calculated as shown below:
Root 1 =
Root 2=
C++ Program
#include #include using namespace std; // ######################################################## // // -b + SQRT( b^2 - 4ac) // Root 1 = ------------------------------- // 2a // // -b - SQRT( b^2 - 4ac) // Root 2 = ------------------------------- // 2a // // // www.TestingDocs.com //########################################################## int main() { float a = 3.0, b = -12.0, c = -36.0; // Equation is 3x^2 -12x - 36 = 0 float sqRootPart = sqrt( b*b - 4*a*c ); //Find the roots float eqRoot1 = (-b + sqRootPart)/(2*a); float eqRoot2 = (-b - sqRootPart)/(2*a); //Output cout << "Root 1 := " << eqRoot1 << endl; cout << "Root 2 := " << eqRoot2 << endl; return 0; }
Sample Output
Root 1 := 6
Root 2 := -2
Process returned 0 (0x0) execution time : 2.083 s
Press any key to continue.
Enhancements
We can further enhance the program to prompt the input values of a, b, c to the user. Right now we have to modify the code for the values.
Generate the equation string based on the values of a, b, and c and display the equation string in the output.
Take into consideration the imaginary roots if the discriminant is less than 0. The logic is outlined in the flowchart link
Flowchart :
https://www.testingdocs.com/questions/raptor-flowchart-to-find-quadratic-equation-roots/
The IDE used in the tutorial is Code:: Blocks. To download and install Code Blocks follow the link:
https://www.testingdocs.com/download-and-install-codeblocks/
For more information on Code Blocks IDE used in the program, visit the official website of Code blocks IDE: