C++ Program To Solve Quadratic Equation Using Function
In this article, you will learn how to write a C++ program to solve quadratic equations by implementing a dedicated function. We will cover the mathematical concepts behind quadratic equations and provide a practical C++ solution.
Problem Statement
A quadratic equation is a polynomial equation of the second degree, commonly expressed in the form $ax^2 + bx + c = 0$, where $a$, $b$, and $c$ are coefficients, and $a \neq 0$. The goal is to find the values of $x$, known as the roots, that satisfy this equation. The nature and number of roots depend on the discriminant, $\Delta = b^2 - 4ac$:
- If $\Delta > 0$, there are two distinct real roots.
- If $\Delta = 0$, there is exactly one real root (a repeated root).
- If $\Delta < 0$, there are two distinct complex roots.
The problem is to create a C++ program that takes the coefficients $a$, $b$, and $c$ as input and calculates its roots using a function, handling all three discriminant scenarios correctly.
Example
Consider the quadratic equation $x^2 - 5x + 6 = 0$.
Given coefficients: $a=1$, $b=-5$, $c=6$.
The program should output:
Root 1 = 3.00
Root 2 = 2.00
Background & Knowledge Prerequisites
To understand and implement the solution effectively, readers should be familiar with:
- C++ Basic Syntax: Variables, data types (especially
doublefor precision), arithmetic operators. - Functions: Declaring, defining, and calling functions, including passing arguments by value and by reference.
- Conditional Statements:
if-else if-elsestructures for decision-making based on the discriminant. - Input/Output Operations: Using
iostreamfor reading user input (cin) and displaying output (cout). - Mathematical Functions: Using functions from the
cmathlibrary, specificallysqrt()for square roots.
Use Cases or Case Studies
Quadratic equations appear in various fields due to their fundamental nature in describing parabolic trajectories and relationships involving squares.
- Physics: Calculating projectile motion, such as the time it takes for a ball thrown upwards to hit the ground.
- Engineering: Designing structures, optimizing beam loads, or analyzing electrical circuits (RLC circuits).
- Economics: Determining optimal production levels where cost and revenue functions are quadratic.
- Geometry: Finding dimensions of shapes based on area or perimeter constraints.
- Computer Graphics: Intersecting rays with spheres or other quadratic surfaces.
Solution Approaches
For solving a quadratic equation, the primary mathematical approach involves the quadratic formula. Our C++ solution will encapsulate this formula within a function to promote modularity and reusability.
Approach 1: Solving Quadratic Equation using a Function
This approach defines a void function that takes the coefficients a, b, c and two reference parameters for storing the calculated roots. Inside the function, it computes the discriminant and then determines the roots based on its value.
// 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;
}
Sample Output
Case 1: Two distinct real roots ($x^2 - 5x + 6 = 0$)
Enter coefficient a: 1
Enter coefficient b: -5
Enter coefficient c: 6
The quadratic equation has two distinct real roots.
Root 1 = 3.00
Root 2 = 2.00
Case 2: One real (repeated) root ($x^2 + 4x + 4 = 0$)
Enter coefficient a: 1
Enter coefficient b: 4
Enter coefficient c: 4
The quadratic equation has one real (repeated) root.
Root = -2.00
Case 3: Two distinct complex roots ($x^2 + 2x + 5 = 0$)
Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 5
The quadratic equation has two distinct complex roots.
Root 1 = -1.00 + 2.00i
Root 2 = -1.00 - 2.00i
Stepwise Explanation
- Include Headers:
-
iostreamis included for standard input (cin) and output (cout).
-
cmath is included for mathematical functions like sqrt() (square root) and fabs() (absolute value for floating-point numbers).iomanip is included for std::fixed and std::setprecision to format the output of floating-point numbers.solveQuadraticFunction Definition:- The function
solveQuadratictakes threedoublearguments (a,b,c) for the coefficients and twodouble&(reference) arguments (root1,root2) to store the calculated roots. Using references allows the function to modify theroot1androot2variables declared inmain.
- The function
discriminant ($b^2 - 4ac$) is calculated.if-else if-else structure checks the discriminant:discriminant >= 0: The roots are real. The quadratic formula is applied directly to find root1 and root2.discriminant < 0: The roots are complex. The real part (-b / 2a) and the imaginary part (sqrt(|discriminant|) / 2a) are calculated. For display purposes, root1 stores the real part and root2 stores the magnitude of the imaginary part. fabs() is used to get the absolute value of the negative discriminant before taking its square root.mainFunction:- Declares variables
a,b,cfor coefficients androot1,root2for storing the results.
- Declares variables
a=0: It checks if a is zero. If it is, the equation is not quadratic. It then further checks if b is also zero. If a=0 and b \neq 0, it's a linear equation ($bx + c = 0$), and it calculates that root. If both a=0 and b=0, it handles cases like $c=0$ (infinite solutions) or $c \neq 0$ (no solution).solveQuadratic function, passing the coefficients and the root variables by reference.std::fixed and std::setprecision(2) to format the output of floating-point numbers to two decimal places.discriminant == 0, it indicates one repeated real root.discriminant > 0, it indicates two distinct real roots.discriminant < 0, it indicates two distinct complex roots and formats the output as real ± imaginary i.0 to indicate successful execution.Conclusion
By implementing the quadratic formula within a dedicated function, we achieve a modular and reusable C++ program to solve quadratic equations. This approach effectively handles all three possible scenarios for roots—distinct real, repeated real, and distinct complex—providing clear and accurate output based on the discriminant. Using functions makes the code more organized, easier to debug, and simpler to integrate into larger applications.
Summary
- A quadratic equation is of the form $ax^2 + bx + c = 0$, where $a \neq 0$.
- The nature of roots depends on the discriminant, $\Delta = b^2 - 4ac$.
- If $\Delta > 0$, there are two distinct real roots.
- If $\Delta = 0$, there is one repeated real root.
- If $\Delta < 0$, there are two distinct complex roots.
- A C++ function can encapsulate the logic for calculating roots, taking coefficients as input and returning roots via reference parameters.
- Robust programs should include error handling for the case where coefficient
ais zero. - The
cmathlibrary provides essential functions likesqrt()andfabs()for these calculations.