C++ Online Compiler
Example: Solve Quadratic Equation using Function in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Solve Quadratic Equation using Function #include <iostream> // For input/output operations #include <cmath> // For sqrt() and fabs() functions #include <iomanip> // For std::fixed and std::setprecision using namespace std; // Function to solve quadratic equation // Takes coefficients a, b, c and outputs roots via reference parameters void solveQuadratic(double a, double b, double c, double& root1, double& root2) { // Step 1: Calculate the discriminant (delta) double discriminant = b * b - 4 * a * c; // Step 2: Determine the nature of roots based on the discriminant if (discriminant >= 0) { // Real roots (distinct or equal) root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); } else { // Complex roots double realPart = -b / (2 * a); double imaginaryPart = sqrt(fabs(discriminant)) / (2 * a); // For complex roots, we'll store the real part in root1 and // the imaginary part (positive value) in root2 to display them in main. // This is a common way to handle complex numbers when not using a complex type. root1 = realPart; root2 = imaginaryPart; // root2 now stores the magnitude of the imaginary part } } int main() { // Step 1: Declare variables for coefficients and roots double a, b, c; double root1, root2; // These will hold the calculated roots // Step 2: Get user input for coefficients cout << "Enter coefficient a: "; cin >> a; cout << "Enter coefficient b: "; cin >> b; cout << "Enter coefficient c: "; cin >> c; // Step 3: Handle the special case where 'a' is zero if (a == 0) { cout << "Error: 'a' cannot be zero for a quadratic equation." << endl; // If a is 0, it becomes a linear equation: bx + c = 0 => x = -c/b if (b != 0) { cout << "This is a linear equation. Root x = " << fixed << setprecision(2) << -c / b << endl; } else { cout << "No solution or infinite solutions." << endl; } return 1; // Indicate an error } // Step 4: Call the function to solve the quadratic equation solveQuadratic(a, b, c, root1, root2); // Step 5: Display the results based on the discriminant's original sign double discriminant = b * b - 4 * a * c; cout << fixed << setprecision(2); // Format output to 2 decimal places if (discriminant >= 0) { if (discriminant == 0) { cout << "The quadratic equation has one real (repeated) root." << endl; cout << "Root = " << root1 << endl; // root1 and root2 would be equal } else { cout << "The quadratic equation has two distinct real roots." << endl; cout << "Root 1 = " << root1 << endl; cout << "Root 2 = " << root2 << endl; } } else { cout << "The quadratic equation has two distinct complex roots." << endl; cout << "Root 1 = " << root1 << " + " << root2 << "i" << endl; cout << "Root 2 = " << root1 << " - " << root2 << "i" << endl; } return 0; }
Output
Clear
ADVERTISEMENTS