题解 | 计算一元二次方程
计算一元二次方程
https://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26
#include <stdbool.h> #include <stdio.h> #include <math.h> int main() { float a, b,c; while (scanf("%f %f %f",&a,&b,&c)!=EOF) { if (a==0) { printf("Not quadratic equation\n"); } else { float derta,x1,x2; derta=b*b-4*a*c; if (derta==0) { x1=-b/(2*a); if (x1==-0.0) { x1=0; } printf("x1=x2=%0.2f\n",x1); } else if(derta>0){ x1=(-b+sqrt(derta))/(2.0*a); x2=(-b-sqrt(derta))/(2.0*a); if(x1<=x2){ printf("x1=%0.2f;x2=%0.2f\n",x1,x2); } else{ float tmp=x1; x1=x2; x2=tmp; printf("x1=%0.2f;x2=%0.2f\n",x1,x2); } } else{ float realPart = -b / (2 * a); float imagPart = sqrt(-derta) / (2 * a); // 处理-0.00的情况 if (realPart == -0.0f) realPart = 0.0f; if (imagPart == -0.0f) imagPart = 0.0f; if (realPart != 0.0f) { printf("x1=%.2f-%.2fi;x2=%.2f+%.2fi\n", realPart, imagPart, realPart, imagPart); } else { printf("x1=%.2fi;x2=%.2fi\n", -imagPart, imagPart); } } } } return 0; }