/* * Program to find real roots of quadratic equation, using a function. * Also prints some "test case" examples. */ #include #include void print_real_roots(double a, double b, double c); int main(void) { /* try to come up with one test for each condition in function code */ print_real_roots(1, 0, -1); print_real_roots(1, -4, 4); print_real_roots(1, 0, 1); print_real_roots(0, 2, 1); print_real_roots(0, 0, 1); print_real_roots(0, 0, 0); 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 */ } print_real_roots(a, b, c); return 0; } void print_real_roots(double a, double b, double c) { printf("finding roots for a = %f, b = %f, c = %f\n", a, b, c); double d = b*b - 4*a*c; if (d < 0) { printf("no real roots\n"); } else if (a != 0) { double r1 = (-b + sqrt(d))/(2*a); double r2 = (-b - sqrt(d))/(2*a); printf("roots for are %f, %f\n", r1, r2); } else if (b != 0) { double r1 = -c / b; printf("root is %f\n", r1); } else { if (c != 0) { printf("no solutions\n"); } else { printf("many solutions\n"); } } printf("\n"); }