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 |
#include <iostream> #include <cmath> #include <complex> // Function to solve the quadratic equation ax^2 + bx + c = 0 void solveQuadratic(double a, double b, double c) { if (a == 0) { std::cerr << "This is not a quadratic equation." << std::endl; return; } double discriminant = b * b - 4 * a * c; 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:" << std::endl; std::cout << "Root 1 = " << root1 << std::endl; std::cout << "Root 2 = " << root2 << std::endl; } else if (discriminant == 0) { // One real root double root = -b / (2 * a); std::cout << "Roots are real and the same:" << std::endl; std::cout << "Root = " << root << std::endl; } else { // Complex roots std::complex<double> root1 = (-b + std::sqrt(std::complex<double>(discriminant))) / (2.0 * a); std::complex<double> root2 = (-b - std::sqrt(std::complex<double>(discriminant))) / (2.0 * a); std::cout << "Roots are complex and different:" << std::endl; std::cout << "Root 1 = " << root1 << std::endl; std::cout << "Root 2 = " << root2 << std::endl; } } int main() { double a, b, c; std::cout << "Enter coefficients a, b, and c: "; std::cin >> a >> b >> c; solveQuadratic(a, b, c); return 0; } |
Explanation
- Quadratic Equation:
- The general form of a quadratic equation is ax2+bx+c=0ax^2 + bx + c = 0 Advertisement
- The general form of a quadratic equation is ax2+bx+c=0ax^2 + bx + c = 0
- Discriminant:
- The discriminant of the quadratic equation is calculated as discriminant=b2−4ac\text{discriminant} = b^2 – 4ac Advertisement
- The nature of the roots depends on the discriminant:
- If the discriminant is positive, the equation has two distinct real roots.
- If the discriminant is zero, the equation has one real root (a repeated root).
- If the discriminant is negative, the equation has two complex roots.
- The discriminant of the quadratic equation is calculated as discriminant=b2−4ac\text{discriminant} = b^2 – 4ac
- Solving the Equation:
- Real Roots: When the discriminant is non-negative, the program calculates the roots using the quadratic formula:
- Complex Roots: When the discriminant is negative, the program uses the
std::complex
type to handle complex numbers.
- Real Roots: When the discriminant is non-negative, the program calculates the roots using the quadratic formula:
- User Input:
- The program prompts the user to enter the coefficients aa, bb, and cc, and then calls the
solveQuadratic
function to solve the equation and display the roots.
- The program prompts the user to enter the coefficients aa, bb, and cc, and then calls the