// ----------------------------------------------- // Solving a given quadratic euation // 2015 (c) Tomonori Kouya, All rights reserved. // To compile: g++ quadratic_eq.cc -o quadratic_eq // ----------------------------------------------- #include #include #include #include #include using namespace std; // Print usage void usage(const char *prog_name) { cout << "[usage] " << prog_name << " [a] [b] [c]" << endl; } inline double sign(double val) { if(val > 0) return 1.0; if(val < 0) return -1.0; return 0.0; } int main(int argc, char *argv[]) { // Coefficients of a quadratic equation double a, b, c, d, a2; complex x[2], sqrt_d; if(argc <= 1) { usage(argv[0]); return EXIT_SUCCESS; } // Set coefficients a = b = c = 0.0; if(argc >= 2) { a = atof(argv[1]); if(argc >= 3) b = atof(argv[2]); if(argc >= 4) c = atof(argv[3]); } // print the given equation cout << a << " * x^2 + (" << b << ") * x + (" << c << ") = 0 " << endl; // Calculate solutions with analytic formulas d = b * b - 4.0 * a * c; sqrt_d = sqrt((complex)d); a2 = 2.0 * a; x[0] = (- b - sign(b) * sqrt_d) / a2; x[1] = c / (a * x[0]); // Print solutions cout << "x[0] = " << setprecision(15) << x[0] << endl; cout << "x[1] = " << setprecision(15) << x[1] << endl; return EXIT_SUCCESS; }