求 ax² + bx + c = 0 的实数根。判别式 d = b² − 4ac:d > 0 有两个根 (−b ± √d) / 2a,d = 0 有一个根,d < 0 没有实根。roots(a, b, c) 显示一行:根的个数,再是根(2 位小数)。比如 x² − 5x + 6 = 0 显示 2 3.00 2.00。
2 3.00 2.00 2 0.28 -1.78 1 -1.00 0
#include <stdio.h>
#include <math.h>
void roots(double a, double b, double c) {
double d = 0;
// 在这里写:算出判别式 d
if (d > 0) {
double x1 = 0, x2 = 0;
// 在这里写:用求根公式算出 x1(取 +)和 x2(取 −)
printf("2 %.2f %.2f\n", x1, x2);
} else if (d == 0) {
printf("1 %.2f\n", -b / (2 * a));
} else {
printf("0\n");
}
}
int main(void) {
roots(1, -5, 6);
roots(2, 3, -1);
roots(1, 2, 1);
roots(1, 1, 1);
return 0;
}
写好了先点「运行」试试示例,没问题再点「提交」。