/* * (same as quadratic-as-function program, but revised to use * function with pointer parameters) * * program to solve quadratic equation a*x*x + b*x + c = 0 and print * roots if any, or a message if no real roots * * first prints some tests/examples * then prompts for a, b, c and computes/prints roots */ #include #include /* comments on functions with their definitions below */ void compute_and_print_roots(float a, float b, float c); int compute_roots(float a, float b, float c, float *r1, float *r2); /* main program */ int main(void) { float a, b, c; /* do some tests/examples first */ compute_and_print_roots(1, 0, 5); compute_and_print_roots(1, 0, -5); compute_and_print_roots(4, 0, -1); compute_and_print_roots(0, 4, 1); compute_and_print_roots(0, 0, 1); compute_and_print_roots(0, 0, 0); /* now prompt for input */ printf("enter a b c\n"); if (scanf("%f %f %f", &a, &b, &c) != 3) { printf("not numbers\n"); return 1; } compute_and_print_roots(a, b, c); return 0; } /* * compute roots of a*x*x + b*x + c = 0 if possible * returns number of roots found */ int compute_roots(float a, float b, float c, float *r1, float *r2) { if (a != 0) { int discrim = b*b - 4*a*c; if (discrim < 0) { return 0; } else { *r1 = (-b + sqrt(discrim))/(2*a); *r2 = (-b - sqrt(discrim))/(2*a); return 2; } } else if (b != 0) { *r1 = -c/b; *r2 = -c/b; return 1; } else { return 0; } } /* * compute and print roots of a*x*x + b*x + c = 0, or a message saying * no real roots */ void compute_and_print_roots(float a, float b, float c) { float r1, r2; int num_roots; printf("a, b, c = %f, %f, %f\n", a, b, c); num_roots = compute_roots(a, b, c, &r1, &r2); if (num_roots == 2) printf("two roots: %f %f\n", r1, r2); else if (num_roots == 1) printf("one root: %f\n", r1); else if (num_roots == 0) printf("no real roots\n"); else printf("internal error! number of roots %d\n", num_roots); }