Index « Previous Next »

Question

The roots of the quadratic equation ax2 + bx + c = 0, a ne 0 are given by the following formula:

quadratic equation formula

In this formula, the term b2 - 4ac is called the discriminant. If b2 - 4ac = 0, then the equation has two equal roots. If b2 - 4ac > 0, the equation has two real roots. If b2 - 4ac < 0, the equation has two complex roots. Write a program that prompts the user to input the value of a (the coefficient of x2), b (the coefficient of x), and c (the constant term) and outputs the roots of the quadratic equation.

Source Code

#include <stdio.h>
#include <math.h>


int main()
{
    float a, b, c, d, root1, root2;

    printf("Enter value of a, b and c : ");
    scanf("%f%f%f", &a, &b, &c);

    d = b * b - 4 * a * c;

    if (d == 0)
    {
        root1 = ( - b) / (2 * a);
        root2 = root1;
        printf("Roots are real & equal, Root1 = %f, Root2 = %f", root1, root2);
    }
    else if (d > 0)
    {
        root1 =  - (b + sqrt(d)) / (2 * a);
        root2 =  - (b - sqrt(d)) / (2 * a);
        printf("Roots are real & distinct, Root1 = %f, Root2 = %f", root1, root2);
    }
    else
    {
        printf("Roots are imaginary");
    }

    return 0;
}

Output

Enter value of a, b and c : 2 5 -3
Roots are real & distinct, Root1 = -3.000000, Root2 = 0.500000