Write a program in C language that calculates the roots of quadratic equation ax 2 +bx+c.
#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, D, root1, root2, realPart, imagPart;
printf("Enter coefficient a: ");
scanf("%lf",&a);
printf("Enter coefficient b: ");
scanf("%lf",&b);
printf("Enter coefficient c: ");
scanf("%lf",&c);
D = b * b - 4 * a * c;
// condition for real and different roots
if (D > 0) {
root1 = (-b + sqrt(D)) / (2 * a);
root2 = (-b - sqrt(D)) / (2 * a);
printf("root1 = %.2lf\nroot2 = %.2lf", root1, root2);
}// condition for real and equal roots
else if (D == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-D) / (2 * a);
printf("root1 = %.2lf+%.2lfi\nroot2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart);
}
scanf("%lf", &a);
return 0;
}
Comments
Leave a comment