/* * 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 void compute_and_print_roots(float a, float b, float c); /* 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 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) { double r1, r2; printf("a, b, c, = %f %f %f\n", a, b, c); if (a != 0) { int discrim = b*b - 4*a*c; if (discrim < 0) { printf("no real roots\n"); } else { r1 = (-b + sqrt(discrim))/(2*a); r2 = (-b - sqrt(discrim))/(2*a); printf("%f %f\n", r1, r2); } } else if (b != 0) { printf("%f\n", -c/b); } else if (c != 0) { printf("no solution\n"); } else { printf("all x's are solutions\n"); } }