Code:
/* *************************************************
Purpose: Solve for the roots of the quadratic equation,
y = a x^2 + b x + c
by means of the quadratic formula,
root = (-b +or- sqrt(b^2 -4. a c))/(2. a)
Variables: a, b, c + Real coefficients of quadratic equation.
d = Discriminant
root1, root2 = Real roots or real part of complex roots.
root1i,root2i = Imaginary part of complex roots.
Input: Values of coefficients in file 167w02cp1c.dat
Output: Tabulated values of coefficients and roots, with
proper heading and captions, in the UNIX xterm window.
************************************************** */
#include <stdio.h> /* Access input/output functions */
#include <math.h> /* Access math functions */
void main(void)
{
/* Float all variables */
double a, b, c, d, root1, root2;
double root1i,root2i;
FILE *fp;
fp = fopen ("167w02cp1c.dat","r"); /* Open input file */
if (fp==NULL) /* Test for file not open */
{ /* Terminate the program */
puts("\nData file 167w02cp1c.dat has failed to open.");
puts("\nProgram cp1.c is terminated.\n");
return;
}
puts("\n Class goes here");
puts("\n 2002");
puts("\n Name goes here");
puts("\n Problem No. 1");
puts("\n Roots of Quadratic Equations");
printf("\n a b c root1 ");
printf(" Root2");
printf("\n -------------------------------------------------");
printf(" ----------------------------------------");
while (! feof(fp)) /* Start of Loop */
{
fscanf (fp,"%1f%*c%1f%*c%1f",&a,&b,&c); /* Input Values */
if (feof(fp)) /* Looks for end of file */
{
puts("\n End of Data. Program cp1 complete,");
break;
}
if (a==0. || b==0. && c==0.) /* Check for invalid data */
{
printf("\n%10.3f%10.3f%10.3f invalid data",a,b,c);
}
else
d = ((b*b)-(4*a*c)); /* Compute the Discriminant */
/* Compute roots for when the discriminant is positive */
if (d>1.0*pow(10,-6))
{
root1 = ((-b)+pow(d,0.5))/(2*a);
root2 = ((-b)-pow(d,0.5))/(2*a);
printf("\n%10.3f%10.3f%10.3f%13.3f%13.3f",
a, b, c, root1, root2);
/* Print Values */
}
/* Compute roots for when the discriminant is negative */
else if (d<-1.0*pow(10,-6))
{
root1 = -b/(2.*a); root2 = root1;
root1i = sqrt(-d)/(2.*a);
root2i = -root1i;
printf("\n%10.3f%10.3f%10.3f%8.3f%8.3f%8.3f%8.3fi",
a, b, c, root1,root1i,root2,root2i); /* Print Values */
}
else
{
root1 = (-b)/(2*a);
root2 = root1;
printf("\n%10.3f%10.3f%10.3f%13.3f%13.3f",
a,b,c,root1,root2);
}
}
} /* End While Loop */