Loading your workspace…
Loading your workspace…
Find the roots of ax² + bx + c = 0 and demonstrate the decision with an else-if ladder that covers distinct, equal and imaginary roots.
#include <stdio.h>
#include <math.h>
int main(void) {
double a, b, c, d, root1, root2, real, imag;
printf("Enter a, b and c:\n");
if (scanf("%lf %lf %lf", &a, &b, &c) != 3) {
printf("Error: invalid input\n");
return 1;
}
if (a == 0) {
printf("Not a quadratic equation\n");
} else {
d = b * b - 4 * a * c;
if (d > 0) {
root1 = (-b + sqrt(d)) / (2 * a);
root2 = (-b - sqrt(d)) / (2 * a);
printf("Roots are real and distinct: %.2f %.2f\n", root1, root2);
} else if (d == 0) {
root1 = -b / (2 * a);
printf("Roots are real and equal: %.2f\n", root1);
} else {
real = -b / (2 * a);
imag = sqrt(-d) / (2 * a);
if (imag < 0) {
imag = -imag;
}
printf("Roots are imaginary: %.2f + i%.2f and %.2f - i%.2f\n", real, imag, real, imag);
}
}
return 0;
}
Input
1 -3 2Output
Enter a, b and c:
Roots are real and distinct: 2.00 1.00Input
0 2 4Output
Enter a, b and c:
Not a quadratic equationThe else-if ladder checks the discriminant from the most specific test to the general one. Exactly one branch runs, so the program never prints two answers for one equation.
Each branch computes only what it needs: the square root is taken only when d is non-negative in the real branches, and only -d inside the imaginary branch.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
1 -3 2
Expected output
Enter a, b and c: Roots are real and distinct: 2.00 1.00
0 2 4
Expected output
Enter a, b and c: Not a quadratic equation
Whether the roots are real and distinct (d > 0), real and equal (d = 0), or imaginary (d < 0).
The formula divides by 2a, so a zero leading coefficient must be caught before the division.
sqrt needs a non-negative argument, and -d is positive when d is negative.
A chain of conditions where only the first true condition's block runs.
sqrt from math.h is accurate and fast; the program needs the library's result.
Back to all RCU 21BCA1C1P lab programs.