In: Computer Science
Write a program that reads three double numbers from the keyboard representing, respectively, the three coefficients a, b, and c of a quadratic equation. Solve the equation using the following formulas:
x1 = ( - b + square root (b2 – 4ac)) / (2a),
x2 = ( - b + square root (b2 – 4ac)) / (2a)
Run your program on the following sample values:
a=1.0, b=3.0,c=2.0
a=0.5, b=0.5,c=0.125
a=1.0, b=3.0,c=10.0
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, discrm, x1, x2, realPart, imgPart;
//taking input coeffcients of ax^2+bx+c
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
discrm = b*b-4*a*c; //calculating b^2-4ac value
//for diff roots calculation
if (discrm > 0){ //if b^2-4ac value greater than
zero then corresponding formula
x1 = (-b+sqrt(discrm))/(2*a);
x2 = (-b-sqrt(discrm))/(2*a);
printf("x1 = %.2lf and x2 = %.2lf",x1 , x2); //printing
fist root x1 and second root x2
}
//for equal roots calculation
else if (discrm == 0){ //if b^2-4ac value equal to zero
then corresponding formula
x1 = x2 = -b/(2*a);
printf("x1 = x2 = %.2lf;", x1); //printing fist root x1
and second root x2
}
// for roots are not real
else{ //if b^2-4ac value equal to less than zero then
corresponding formula
realPart = -b/(2*a);
imgPart = sqrt(-discrm)/(2*a);
//printing fist root x1 and second root x2
printf("x1 = %.2lf+%.2lfi and x2 = %.2f-%.2fi", realPart, imgPart,
realPart, imgPart);
}
return 0;
}
-------------------------------------------------------------------------------------------------------------------------------------