Loading your workspace…
Loading your workspace…
Accept the coefficients a, b and c of ax² + bx + c = 0 and print the roots, handling the linear case and the real, equal and complex root cases.
#include <stdio.h>
#include <math.h>
int main(void) {
double a, b, c, d, r1, r2, real, imag;
printf("Enter coefficients a, b, c:\n");
if (scanf("%lf %lf %lf", &a, &b, &c) != 3) {
printf("Error: invalid input\n");
return 1;
}
if (a == 0) {
if (b == 0) {
if (c == 0) {
printf("Infinitely many solutions\n");
} else {
printf("No solution\n");
}
} else {
printf("Linear equation, root = %.2f\n", -c / b);
}
return 0;
}
d = b * b - 4 * a * c;
if (d > 0) {
r1 = (-b + sqrt(d)) / (2 * a);
r2 = (-b - sqrt(d)) / (2 * a);
printf("Two distinct real roots: %.2f and %.2f\n", r1, r2);
} else if (d == 0) {
r1 = -b / (2 * a);
printf("Two equal real roots: %.2f\n", r1);
} else {
real = -b / (2 * a);
imag = sqrt(-d) / (2 * a);
if (imag < 0) {
imag = -imag;
}
printf("Two complex roots: %.2f + %.2fi and %.2f - %.2fi\n", real, imag, real, imag);
}
return 0;
}
Input
1 -3 2Output
Enter coefficients a, b, c:
Two distinct real roots: 2.00 and 1.00Input
1 2 5Output
Enter coefficients a, b, c:
Two complex roots: -1.00 + 2.00i and -1.00 - 2.00iInput
0 2 -4Output
Enter coefficients a, b, c:
Linear equation, root = 2.00The discriminant D = b² - 4ac decides the nature of the roots. Its sign is checked before taking a square root, because the square root of a negative number is not a real value; the complex branch takes the root of -D instead.
The a == 0 check comes first because the quadratic formula divides by 2a. Without that guard the program would divide by zero and print nan or inf instead of a meaningful message.
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 coefficients a, b, c: Two distinct real roots: 2.00 and 1.00
1 2 5
Expected output
Enter coefficients a, b, c: Two complex roots: -1.00 + 2.00i and -1.00 - 2.00i
0 2 -4
Expected output
Enter coefficients a, b, c: Linear equation, root = 2.00
D = b² - 4ac. Positive means two distinct real roots, zero means one repeated real root, and negative means two complex conjugate roots.
sqrt needs a non-negative argument for a real result. Since d is negative in that branch, -d is positive and its square root is the imaginary part.
The formula divides by 2a, so a zero leading coefficient would divide by zero. The equation is linear in that case.
math.h declares sqrt. On many systems the program must be linked with the maths library, for example gcc file.c -lm.
%f prints six decimal places by default. %.2f limits the output to two places, matching the currency-like precision typical of lab answers.
Back to all VTU BPOPS103 lab programs.