Skip to main content

Roots of quadratic equation in C

Short answer

Compute discriminant d = b^2 - 4ac. If d>0, real distinct roots (-b±√d)/(2a); d=0, one real root -b/(2a); d<0, complex -b/(2a) ± i√(-d)/(2a). Handle a=0.

Write a program in C to find all possible roots of a quadratic equation ax²+bx+c=0.

For ax² + bx + c = 0, the discriminant is d = b² - 4ac, and the roots are x = (-b ± √d) / 2a.

  • d > 0: two real and distinct roots
  • d = 0: two real and equal roots, x = -b / 2a
  • d < 0: two complex roots, -b/2a ± i √(-d)/2a
#include <stdio.h>
#include <math.h>
int main(void)
{
    float a, b, c, d, r1, r2, re, im;
    printf("Enter a, b, c: ");
    scanf("%f %f %f", &a, &b, &c);
    if (a == 0)
    {
        if (b != 0)
            printf("Linear equation, root = %.2f\n", -c / b);
        else
            printf("Not an equation\n");
        return 0;
    }
    d = b * b - 4 * a * c;
    if (d > 0)
    {
        r1 = (-b + sqrt(d)) / (2 * a);
        r2 = (-b - sqrt(d)) / (2 * a);
        printf("Real and distinct roots: %.2f and %.2f\n", r1, r2);
    }
    else if (d == 0)
    {
        r1 = -b / (2 * a);
        printf("Real and equal roots: %.2f and %.2f\n", r1, r1);
    }
    else
    {
        re = -b / (2 * a);
        im = sqrt(-d) / (2 * a);
        printf("Complex roots: %.2f + %.2fi and %.2f - %.2fi\n", re, im, re, im);
    }
    return 0;
}

Output for a = 1, b = 2, c = 5:

Enter a, b, c: Complex roots: -1.00 + 2.00i and -1.00 - 2.00i

Other test runs: a = 1, b = -5, c = 6 gives Real and distinct roots: 3.00 and 2.00; a = 1, b = -2, c = 1 gives Real and equal roots: 1.00 and 1.00.

The program also handles a = 0 (the equation is linear) so there is no division by zero. Compile with -lm for sqrt.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →