/* * Program to find real roots of quadratic equation, using a function with * pointer arguments. * * FIXME -- need to figure out printing, error checking */ #include #include /* * returns: * how many roots were found, unless special case of a, b, c, all zero, * then -1 */ int find_real_roots(double a, double b, double c, double *r1, double *r2); void print_solution(int root_return_value, double r1, double r2); /* * FIXME add this? * calculate roots and print void test(double a, double b, double c); */ int main(void) { /* FIXME test cases from previous version 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 */ } double r1, r2; int r = find_real_roots(a, b, c, &r1, &r2); printf("a = %f, b = %f, c = %f\n", a, b, c); print_solution(r, r1, r2); return 0; } int find_real_roots(double a, double b, double c, double *r1, double *r2) { double d = b*b - 4*a*c; if (d < 0) { return 0; } if (a != 0) { *r1 = (-b + sqrt(d))/(2*a); *r2 = (-b - sqrt(d))/(2*a); return 2; } else if (b != 0) { *r1 = -c / b; *r2 = *r1; return 1; } else { if (c != 0) { return 0; } else { return -1; } } } void print_solution(int root_return_value, double r1, double r2) { switch (root_return_value) { case 2: printf("two roots %f %f\n", r1, r2); break; case 1: printf("one root %f\n", r1); break; case 0: printf("no (real) solutions\n"); break; case -1: printf("everything a solution!\n"); break; default: printf("should not happen!\n"); } }