Description
Use the formula x1 = (-b + sqrt(b b-4 a c))/(2 a), x2 = (-b-sqrt(b b-4 a c))/(2 a) to find a quadratic The root of the equation ax2+bx+c=0, where a is not equal to 0.
Input
Enter a line containing three floating-point numbers a, b, c (separated by a space), which represent the coefficients of the equation ax2 + bx + c =0.
Output
One line is output, indicating the solution of the equation.
If b2 = 4 * a * c, then the two real roots are equal, and the output form is: x1=x2=...
If b2> 4 * a * c, then the two real roots are not equal, the output form is: x1=...; x2 = …, where x1>x2.
If b2 <4 * a * c, there are two imaginary roots, and output: x1=real part + imaginary part i; x2=real part-imaginary part i, that is, the imaginary part coefficient of x1 is greater than or equal to the imaginary part coefficient of x2 , Cannot be omitted when the real part is 0. Real part = -b / (2 a), imaginary part = sqrt(4 a c-b b) / (2*a)
All real numbers are required to be accurate to 5 digits after the decimal point, and there are no spaces between numbers and symbols.
Sample input
Sample input 1
1.0 2.0 8.0
Sample input 2
1 0 1
Sample output
Sample output 1
x1=-1.00000+2.64575i; x2=-1.00000-2.64575i
Sample output 2
x1=0.00000+1.00000i; x2=0.00000-1.00000i
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float a,b,c,x1,x2,temp;
cin>>a>>b>>c;
temp = b*b-4*a*c;
if(temp == 0)
{
x1 = x2 = (-b + sqrt(b*b-4*a*c))/(2*a);
printf("x1=x2=%.5f",x1);
} else if(temp>0){
x1 = (-b + sqrt(b*b-4*a*c))/(2*a);
x2 = (-b - sqrt(b*b-4*a*c))/(2*a);
printf("x1=%.5f;x2=%.5f",x1,x2);
}else{
x1 = -b / (2*a);
x2 = sqrt(4*a*c-b*b) / (2*a);
if(abs(x1) < 0.00001)
{
x1 = 0.00000;
}
if(abs(x2) < 0.00001)
{
x2 = 0.00000;
}
printf("x1=%.5f+%.5fi;x2=%.5f-%.5fi",x1,x2,x1,x2);
}
return 0;
}