/* * Find real roots of quadratic equation: * Prompt for coefficients. * Print roots if they exist, else message. Also do simple checking * that input is okay. * * This version packages the code to solve and print results in * a function and solves some examples/tests before prompting. * * Compile with -lm for sqrt. */ #include #include /* * function to compute and print roots of a*x*x + b*x + c = 0. */ void compute_and_print(double a, double b, double c); /* main function */ int main(void) { printf("program to solve a*x*x + b*x + c = 0\n"); printf("examples/tests:\n\n"); /* examples that try to cover all the different possibilities */ /* 2*x*x - 8 = 0 (two roots) */ compute_and_print(2.0, 0.0, -8.0); /* (2x+1)*(x+5) = 0 (two roots) */ compute_and_print(2.0, 11.0, 5.0); /* 1*x*x + 2 = 0 (no roots) */ compute_and_print(1.0, 0.0, 2.0); /* 1*x*x = 0 (one root) */ compute_and_print(1.0, 0.0, 0.0); /* 2*x - 5 = 0 (linear, one root) */ compute_and_print(0.0, 2.0, 5.0); /* 5 = 0 (does this have a name? no roots) */ compute_and_print(0.0, 0.0, 5.0); /* 0 = 0 (does this have a name? all roots) */ compute_and_print(0.0, 0.0, 0.0); double a, b, c; printf("enter coefficients a, b, c (floating-point)\n"); if (scanf("%lf %lf %lf", &a, &b, &c) != 3) { printf("error: non-numeric input\n"); return 1; } compute_and_print(a, b, c); return 0; } void compute_and_print(double a, double b, double c) { printf("for a = %f, b = %f, c = %f:\n", a, b, c); /* check for cases where the formula does not work */ if (a == 0) { if (b == 0) { if (c == 0) { printf("all coefficients zero, so everything is a root\n\n"); } else { printf("no roots\n\n"); } } else { printf("one root %f\n\n", -c/b); } } else { /* compute discrim and test for < 0 (no roots) */ double discrim = b*b - 4*a*c; if (discrim < 0) { printf("no real roots\n\n"); } else if (discrim == 0) { printf("one root %f\n\n", -b / (2*a)); } else { printf("two roots %f %f\n\n", (-b + sqrt(discrim)) / (2*a), (-b - sqrt(discrim)) / (2*a)); } } }