1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
#include <iostream> #include <cmath> #include <stdexcept> // Function to calculate the roots of the quadratic equation void solveQuadraticEquation(double a, double b, double c) { // Check if the equation is actually quadratic if (a == 0) { throw std::invalid_argument("Coefficient 'a' cannot be zero for a quadratic equation."); } // Calculate the discriminant double discriminant = b * b - 4 * a * c; std::cout << "Solving equation: " << a << "x^2 + " << b << "x + " << c << " = 0\n"; // Check the discriminant value if (discriminant > 0) { // Two distinct real roots double root1 = (-b + std::sqrt(discriminant)) / (2 * a); double root2 = (-b - std::sqrt(discriminant)) / (2 * a); std::cout << "Roots are real and different.\n"; std::cout << "Root 1: " << root1 << "\n"; std::cout << "Root 2: " << root2 << "\n"; } else if (discriminant == 0) { // One real root (repeated) double root = -b / (2 * a); std::cout << "Roots are real and the same.\n"; std::cout << "Root: " << root << "\n"; } else { // Complex roots double realPart = -b / (2 * a); double imaginaryPart = std::sqrt(-discriminant) / (2 * a); std::cout << "Roots are complex and different.\n"; std::cout << "Root 1: " << realPart << " + " << imaginaryPart << "i\n"; std::cout << "Root 2: " << realPart << " - " << imaginaryPart << "i\n"; } } int main() { // Example coefficients for the quadratic equation double a = 1.0, b = -3.0, c = 2.0; try { solveQuadraticEquation(a, b, c); } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << "\n"; } return 0; } |
Explanation
- solveQuadraticEquation Function:
- Parameters: Takes three coefficients < code>a Advertisement
b
, andc
representing the quadratic equation ax2+bx+c=0ax^2 + bx + c = 0. - Discriminant Calculation: Computes the discriminant using the formula b2−4acb^2 – 4ac Advertisement
- If the discriminant is positive, the equation has two distinct real roots.
- If the discriminant is zero, the equation has one repeated real root.
- If the discriminant is negative, the equation has two complex conjugate roots.
- Root Calculation: Based on the discriminant, the program calculates and prints the roots of the equation.
Advertisement - Parameters: Takes three coefficients < code>a
- main Function:
- Provides example coefficients for the quadratic equation.
- Calls
solveQuadraticEquation
to solve the equation and display the roots. - Handles any exceptions thrown by the function (e.g., when the coefficient
a
is zero, which would make it a linear equation instead).