题解 | #计算一元二次方程#
计算一元二次方程
https://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, root, x1, x2;
while (scanf("%lf %lf %lf", &a, &b, &c) != EOF) {
getchar();
if (a == 0) {
printf("Not quadratic equation\n");
} else if (a != 0) {
root = pow(b, 2) - (4 * a * c);
// 两个根相等
if (root == 0) {
// 求根公式
x1 = ((-b) + sqrt(root)) / (2 * a);
// 将-0.00变为0
x1 == 0 ? x1 = 0 : x1;
printf("x1=x2=%.2lf\n", x1);
}
// 两个根不等
else if (root > 0) {
// 求根公式
double temp;
x1 = ((-b) + sqrt(root)) / (2 * a);
x2 = ((-b) - sqrt(root)) / (2 * a);
// 检测x1 <= x2?
x1 <= x2 ?
printf("x1=%.2lf;x2=%.2lf\n", x1, x2) :
printf("x1=%.2lf;x2=%.2lf\n", x2, x1);
}
// 两个虚根
else if (root < 0) {
// 求虚根1的实部x1,虚部x2
x1 = (-b) / (2 * a);
x2 = sqrt(-root) / (2 * a);
printf("x1=%.2lf-%.2lfi;", x1, x2);
// 求虚根2的实部x1,虚部x2
x1 = (-b) / (2 * a);
x2 = sqrt(-root) / (2 * a);
printf("x2=%.2lf+%.2lfi\n", x1, x2);
}
}
}
return 0;
}
