Quadratic equation in C, Objective-C, C++
Example for versions
Borland C++ Builder 6,
Microsoft Visual C++ 9 (2008),
g++ 3.4.5,
gcc 3.4.5,
gcc 3.4.5 (Objective-C),
gcc 4.2.4,
tcc 0.9.25
This example works both for C and C++, as well as for Objective-C which is superset of C.
#include <math.h>
#include <stdio.h>
int main()
{
int A, B, C;
double D;
printf("A = ");
scanf("%d", &A);
if (A == 0) {
printf("Not a quadratic equation.\n");
return 0;
}
printf("B = ");
scanf("%d", &B);
printf("C = ");
scanf("%d", &C);
D = B * B - 4 * A * C;
if (D == 0) {
printf("x = %f\n", -B / 2.0 / A);
return 0;
}
if (D > 0) {
printf("x1 = %f\nx2 = %f\n",
(-B + sqrt(D)) / 2.0 / A, (-B - sqrt(D))/ 2.0 / A);
} else {
printf("x1 = (%f, %f)\nx2 = (%f, %f)\n",
-B / 2.0 / A, sqrt(-D) / 2.0 / A, -B / 2.0 / A, -sqrt(-D) / 2.0 /A);
}
return 0;
}
Comments
]]>blog comments powered by Disqus
]]>