Quadratic equation in C
Example for versions
gcc 4.2.4
This example requires C99, since it uses complex
type introduced in it.
#include <stdio.h>
#include <complex.h>
#include <math.h>
void print(int ind, double complex x) {
printf("x%d = ", ind);
if (fabs(cimag(x)) < 1e-6)
printf("%f\n", creal(x));
else printf("(%f, %f)\n", creal(x), cimag(x));
}
int main() {
double A, B, C;
double D;
printf("A = ");
scanf("%lf", &A);
if (fabs(A)<1E-3) {
printf("Not a quadratic equation\n");
return 1;
}
printf("B = ");
scanf("%lf", &B);
printf("C = ");
scanf("%lf", &C);
A *= 2;
D = B*B-A*C*2.0;
if (fabs(D)<1E-3)
printf("x = %f", creal(-B/A));
else {
print(1, (-B+csqrt(D))/A);
print(2, (-B-csqrt(D))/A);
}
return 0;
}
Comments
]]>blog comments powered by Disqus
]]>