#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("Roots are real and different.\n"); printf("Root1 = %.2f\n", root1); printf("Root2 = %.2f\n", root2); } else if (discriminant == 0) { root1 = root2 = -b / (2 * a); printf("Roots are real and same.\n"); printf("Root1 = Root2 = %.2f\n", root1); } else { realPart = -b / (2 * a); imaginaryPart = sqrt(-discriminant) / (2 * a); printf("Roots are complex and different.\n"); printf("Root1 = %.2f + %.2fi\n", realPart, imaginaryPart); printf("Root2 = %.2f - %.2fi\n", realPart, imaginaryPart); } return 0; }
Inside the main() function:
- Float variables `a`, `b`, `c`, `discriminant`, `root1`, `root2`, `realPart`, and `imaginaryPart` are declared to store the coefficients of the quadratic equation, discriminant, roots, real part, and imaginary part respectively.
- The user is prompted to enter the coefficients of the quadratic equation.
- Discriminant is calculated using the formula b^2 - 4ac.
- Based on the value of discriminant, the nature of roots (real, equal, or complex) is determined and printed along with the roots.