/* * Program to find real roots of quadratic equation, using a function with * pointer arguments. */ #include #include /* * returns: * how many roots were found, unless special case of a, b, c, all zero, * then -1 */ int compute_roots(double a, double b, double c, double *r1, double *r2); /* * print solution */ void print_solution(int num_roots, double r1, double r2); /* * calculate roots and print */ void demo(double a, double b, double c); /* * main program */ int main(void) { demo(1, -1, -6); demo(1, 0, 4); demo(0, 5, 2); demo(0, 0, 0); demo(0, 0, 5); printf("enter coefficients a, b, c\n"); double a, b, c; if (scanf("%lf %lf %lf", &a, &b, &c) != 3) { printf("invalid input\n"); return 1; /* bail out of program */ } double r1, r2; int nroots = compute_roots(a, b, c, &r1, &r2); printf("a = %f, b = %f, c = %f\n", a, b, c); print_solution(nroots, r1, r2); /* in a real program we might do something else with the roots */ return 0; } int compute_roots(double a, double b, double c, double *r1, double *r2) { if (a == 0) { if (b == 0) { if (c != 0) { return 0; } else { return -1; } } else { *r1 = -c/b; return 1; } } else { double d = b*b - 4*a*c; if (d < 0) { return 0; } else { *r1 = (-b + sqrt(d)) / (2*a); *r2 = (-b - sqrt(d)) / (2*a); return 2; } } } void print_solution(int num_roots, double r1, double r2) { switch (num_roots) { case 2: printf("two roots %f %f\n", r1, r2); break; case 1: printf("one root %f\n", r1); break; case 0: printf("no roots\n"); break; case -1: printf("everything a root\n"); break; default: printf("invalid number of roots (should not happen)\n"); } } void demo(double a, double b, double c) { double r1, r2; int nroots = compute_roots(a, b, c, &r1, &r2); printf("a = %f, b = %f, c = %f\n", a, b, c); print_solution(nroots, r1, r2); }