题解 | #计算一元二次方程#
计算一元二次方程
http://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26
#include<stdio.h>
#include<math.h>
int main() {
float a, b, c;
while (scanf("%f %f %f", &a, &b, &c) != EOF) {
if (a != 0) {
//一元二次方程的根的判别式为:△=b2-4ac
float d = b * b - 4 * a * c;
float val = -b + sqrt(d);
if (d == 0)
if (val == 0)
//sqrt是math.h头文件中求值平方根
printf("x1=x2=%.2f\n", val);
else
printf("x1=x2=%.2f\n", val / 2 / a);
else if (d > 0)
printf("x1=%.2f;x2=%.2f\n", (-b - sqrt(d)) / 2 / a, (-b + sqrt(d)) / 2 / a);
else if (-b == 0)
printf("x1=%.2f-%.2fi;x2=%.2f+%.2fi\n", b / 2 / a, sqrt(-d) / 2 / a,
b / 2 / a, sqrt(-d) / 2 / a);
else {
float val = sqrt(-d) / 2 / a;
if (val < 0) val = -val;
printf("x1=%.2f-%.2fi;x2=%.2f+%.2fi\n", -b / 2 / a, val,
-b / 2 / a, val);
}
} else printf("Not quadratic equation\n");
}
return 0;
}
#include<math.h>
int main() {
float a, b, c;
while (scanf("%f %f %f", &a, &b, &c) != EOF) {
if (a != 0) {
//一元二次方程的根的判别式为:△=b2-4ac
float d = b * b - 4 * a * c;
float val = -b + sqrt(d);
if (d == 0)
if (val == 0)
//sqrt是math.h头文件中求值平方根
printf("x1=x2=%.2f\n", val);
else
printf("x1=x2=%.2f\n", val / 2 / a);
else if (d > 0)
printf("x1=%.2f;x2=%.2f\n", (-b - sqrt(d)) / 2 / a, (-b + sqrt(d)) / 2 / a);
else if (-b == 0)
printf("x1=%.2f-%.2fi;x2=%.2f+%.2fi\n", b / 2 / a, sqrt(-d) / 2 / a,
b / 2 / a, sqrt(-d) / 2 / a);
else {
float val = sqrt(-d) / 2 / a;
if (val < 0) val = -val;
printf("x1=%.2f-%.2fi;x2=%.2f+%.2fi\n", -b / 2 / a, val,
-b / 2 / a, val);
}
} else printf("Not quadratic equation\n");
}
return 0;
}