#include <iostream> #include <cmath> using namespace std; const int NO_SOLUTION = 0; const int ONE_REAL_SOLUTION = 1; const int TWO_REAL_SOLUTIONS = 2; const int ALL_REALS = 3; const int NO_REAL_SOLUTIONS = 4; int linear(double a, double b, double& outX); int quadratic(double a, double b, double c, double& outX1, double& outX2); int main() { double a, b, c,x1,x2; cout << "Enter the quadratic equation coefficients" << endl; cin >> a >> b >> c; switch (quadratic(a,b,c,x1,x2)) { case NO_SOLUTION: cout << "No solutions" << endl; break; case ONE_REAL_SOLUTION: cout << "One solution: " << x1 << endl; break; case TWO_REAL_SOLUTIONS: cout << "Two real solutions: " << x1 << " and " << x2 << endl; break; case ALL_REALS: cout << "All real number are solutions" << endl; break; case NO_REAL_SOLUTIONS: cout << "No real solutions" << endl; break; } return 0; } int quadratic(double a, double b, double c, double& outX1, double& outX2) { double delta, x1, x2; delta = b * b - 4 * a * c; if (delta != 0.0) { if (delta > 0) { x1 = (-b + sqrt(delta)) / (2 * a); x2 = (-b - sqrt(delta)) / (2 * a); outX1 = x1; outX2 = x2; return TWO_REAL_SOLUTIONS; } else if (delta == 0.0) { x1 = -b / (2 * a); return ONE_REAL_SOLUTION; } else return NO_REAL_SOLUTIONS; } else return linear(b, c, outX1); } int linear(double a, double b, double& outX) { double x; if (a != 0) { x = -b / a; outX = x; return ONE_REAL_SOLUTION; } else if ((a == 0) && (b == 0)) { x = 0; outX = x; return ALL_REALS; } else return NO_SOLUTION; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter