C Program - Find All Roots of a Quadratic Equation

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

int main() {
    float a, b, c, discriminant, root1, root2, realPart, imaginaryPart;

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

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

    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2*a);
        root2 = (-b - sqrt(discriminant)) / (2*a);
        printf("Real and Distinct Roots: %.2f and %.2f\n", root1, root2);
    }
    else if (discriminant == 0) {
        root1 = root2 = -b / (2*a);
        printf("Real and Equal Roots: %.2f and %.2f\n", root1, root2);
    }
    else {
        realPart = -b / (2*a);
        imaginaryPart = sqrt(-discriminant) / (2*a);
        printf("Complex Roots: %.2f + %.2fi and %.2f - %.2fi\n",
                realPart, imaginaryPart, realPart, imaginaryPart);
    }

    return 0;
}
Enter coefficients a, b and c: 1 -3 2
Real and Distinct Roots: 2.00 and 1.00

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...