/* --------------------------------------------------------------------- // Figure 5.10 and 5.11: Quadratic roots. // Solve a quadratic equation with any coefficients a, b, and c. // Test for degenerate equations and account for single roots and // complex roots. // ------------------------------------------------------------------------ */ #include "tools.h" void main( void ) { double a, b, c; /* Coefficients of the equation. */ double d, two_a, sroot; /* Working storage. */ double xreal, ximag, x1, x2; /* Answers. */ banner(); puts( " Find the roots of ax*x + bx + c = 0" ); printf( " Enter the values of a, b, and c: " ); scanf( "%lg%lg%lg", &a, &b, &c ); printf( "\n The equation is %g *x*x + %g *x + %g = 0\n", a, b, c ); if (a == 0 && b == 0) { printf( " Degenerate equation -- no roots\n" ); } else if (a == 0) { printf( " Linear equation -- root at -c/b = %g\n", -c/b ); } else { two_a = 2 * a; d = b * b - 4 *a * c; /* discriminant of equation. */ sroot = sqrt( fabs(d) ); /* fabs is floating point absolute value. */ if (d < 0) { /* If d is negative the roots are complex. */ xreal = -b / two_a; ximag = sroot / two_a; printf( "\n The roots are x = %g + %g i and x = %g - %g i \n", xreal, ximag, xreal, ximag ); } else if (d == 0) { /* There is only one root. */ printf( "\n Single real root at x = %g \n", -b / two_a ); } else { /* If d is positive the roots are real. */ x1 = -b / two_a + sroot / two_a; x2 = -b / two_a - sroot / two_a; printf( "\n The real roots are x = %g and %g \n", x1, x2 ); } } bye(); }