1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
/* resolve Quadratic Equation */
#include <stdio.h>
#include <math.h>
#include <float.h>
static void purge (FILE * fp)
{
int c;
while ((c = fgetc (fp)) != '\n' && c != EOF)
{
}
}
static void print_quad (double a, double b, double c)
{
int started = 0;
if (fabs (a) > DBL_EPSILON)
{
printf ("%.2fx^2", a);
started = 1;
}
if (fabs (b) > DBL_EPSILON)
{
if (started)
{
int sign = '+';
if (b < 0)
{
sign = '-';
}
printf (" %c %.2fx", sign, fabs (b));
}
else
{
printf ("%.2fx", b);
started = 1;
}
}
if (fabs (c) > DBL_EPSILON)
{
if (started)
{
int sign = '+';
if (c < 0)
{
sign = '-';
}
printf (" %c %.2f", sign, fabs (c));
}
else
{
printf ("%.2f", c);
}
}
printf ("\n");
}
static void print_quad_roots (double a, double b, double c)
{
double delta = b * b - 4 * a * c;
if (delta > 0)
{
// print the roots of delta
printf ("x1 = %.2f\n", (-b + sqrt (delta)) / 2 * a);
printf ("x2 = %.2f\n", (-b - sqrt (delta)) / 2 * a);
}
else
{
printf ("no real roots\n");
}
}
int main (void)
{
double a, b, c;
int n;
do
{
printf ("enter a,b,and c values: ");
n = scanf ("%lf%lf%lf", &a, &b, &c);
if (n != 3)
{
purge (stdin);
}
}
while (n != 3);
print_quad (a, b, c);
print_quad_roots (a, b, c);
return 0;
} |