/* * Program to find roots of a quadratic equation. * No input for now -- input is hardcoded. */ #include #include void roots(double a, double b, double c); int main(void) { roots(1.0, 0.0, 1.0); roots(1.0, 0.0, 4.0); roots(1.0, 0.0, 0.0); roots(1.0, 0.0, -1.0); roots(1.0, -2.0, 1.0); // (x-1)(x-1) roots(2.0, -5.0, 2.0); // (2x-1)*(x-2) roots(0.0, 1.0, 1.0); roots(0.0, 0.0, 1.0); roots(0.0, 0.0, 0.0); return 0; } /* print root(s) of a*x*x + b*x + c = 0, or message if none */ void roots(double a, double b, double c) { double discrim = b*b - 4*a*c; printf("a = %f, b = %f, c = %f\n", a, b, c); if (a == 0) { if (b == 0) { if (c == 0) { printf("everything is a root\n"); } else { printf("no real roots\n"); } } else { printf("root is %g\n", c/b); } } else if (discrim < 0) { printf("no real roots\n"); } else if (discrim == 0) { printf("one real root: %g\n", -b / (2*a)); } else { printf("two real roots: %g, %g\n", (-b + sqrt(discrim)) / (2*a), (-b - sqrt(discrim)) / (2*a)); } }