Thursday, February 12, 2015

Solution of Quadratic Equation

Here is the code for calculating the root(s) of a quadratic equation.


/* Note: compile with -lm option to link with the math library (for sqrt())
   e.g.: gcc quadratic.c -lm
#include <stdio.h>
#include <math.h>

int main()
    int a, b, c, disc;

    printf("Enter the values for a, b, and c: ");
    scanf("%d%d%d", &a, &b, &c);

    disc = (b*b)-(4*a*c); /* discriminant */

    if(disc>0) /* Two real roots */
        printf("The solutions are %f and %f\n", (-b+sqrt(disc))/(2*a), (-b-sqrt(disc))/(2*a));
    else if(disc<0) /* Two imaginary roots */
        printf("The solutions are %d+%f i and %d-%f i\n", -b/2, sqrt(-disc)/(2*a), -b/2, sqrt(-disc)/(2*a));
    else /* Single real root */
        printf("The solution is %f\n", (float)(-b)/(2*a));

    return 0;


Enter the values for a, b, and c: 1 -10 34
The solutions are 5+3.000000 i and 5-3.000000 i

No comments:

Post a Comment