Find the roots of ax² + bx + c = 0 for three equations, covering two real roots, one repeated root and complex roots.
#include <math.h>
#include <stdio.h>
static void solve(double a, double b, double c) {
double d = b * b - 4 * a * c;
printf("a=%g b=%g c=%g: ", a, b, c);
if (d > 0)
printf("%.2f, %.2f\n", (-b + sqrt(d)) / (2 * a), (-b - sqrt(d)) / (2 * a));
else if (d == 0)
printf("%.2f (repeated)\n", -b / (2 * a));
else
printf("%.2f +/- %.2fi\n", -b / (2 * a), sqrt(-d) / (2 * a));
}
int main(void) {
solve(2, -7, 3);
solve(4, 4, 1);
solve(1, -2, 10);
return 0;
}
a=2 b=-7 c=3: 3.00, 0.50 a=4 b=4 c=1: -0.50 (repeated) a=1 b=-2 c=10: 1.00 +/- 3.00i
The discriminant b² − 4ac selects the case; sqrt of its absolute value gives the real or imaginary part.