/* * Find real roots of quadratic equation: * Prompt for coefficients. * Print roots if they exist, else message. Also do simple checking * that input is okay. * * Compile with -lm for sqrt. */ #include #include int main(void) { 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; } /* 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"); } else { printf("no roots\n"); } } else { printf("one root %f\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"); } else if (discrim == 0) { printf("one root %f\n", -b / (2*a)); } else { printf("two roots %f %f\n", (-b + sqrt(discrim)) / (2*a), (-b - sqrt(discrim)) / (2*a)); } } return 0; }