Hey I am new to the whole C programming and I am trying to write simple code that computes the roots of the quadratic equation and prints the coefficients and the roots into a seperate text file, roots.txt. The coefficients are found in a text file input_equations.txt. Here is my text file
1 -3 2
1 0 -4.84
1 0 1
And here is my program, I am getting wacky numbers in the roots.txt file and I cant seem to work it out.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int compute_roots(double a, double b, double c, double *root1, double *root2)
{
double disc;
disc = pow(b,2) - (4.0*a*c);
if (disc < 0)
{
return (0);
}
if (disc >= 0)
{
*root1 = (-1.0*b+sqrt(disc))/(2.0*a);
*root2 = (-1.0*b-sqrt(disc))/(2.0*a);
return (1);
}
}
int main()
{
double a,b,c,root1,root2;
FILE *inp, outp;
inp = fopen("input_equations.txt", "r");
outp = fopen("roots.txt", "w");
while (fscanf(inp, "%f %f %f", &a, &b, &c) != EOF)
{
fprintf(outp, "%f %f %f ", a, b, c);
if(compute_roots(a, b, c, &root1, &root2) == 1)
fprintf(outp, "root1 = %g root2 = %g\n", root1, root2);
else
fprintf(outp, "The roots are not real numbers.\n");
}
fclose(inp);
fclose(outp);
return(0);
}
It compiles fine, but the output into the roots.txt file is not giving the right coefficients. Any help would be great, I just can't seem to find the bug! Thanks alot!