#include <stdio.h>
#include <math.h>
int main() {
float a, b, c;
float discriminant, root1, root2;
printf("Please enter the three coefficients of a quadratic equation with one variable:\n");
scanf("%f %f %f", &a, &b, &c);
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("This equation has two real roots:%.2f and %.2f\n", root1, root2);
} else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("This equation has a real root:%.2f\n", root1);
} else {
float realPart = -b / (2 * a);
float imagPart = sqrt(-discriminant) / (2 * a);
printf("The equation has two imaginary roots:%.2f+%.2fi and %.2f-%.2fi\n", realPart, imagPart, realPart, imagPart);
}
return 0;
}
在代码设计方面仍存在以下问题:
1、未对用户输入的系数进行有效性检查,例如检查a是否为0,b和c是否为有效的浮点数。
2、当程序在计算复数根时,没有对负数求平方根的情况进行处理,可能会导致程序出现错误或崩溃。
3、在输出的结果中,根的个数可能会存在误差。例如,当判别式的值非常接近0时,可能会被误判为只有一个实根。
4、在输出结果中,根的格式化可能不够准确。例如,当输出虚部时,程序应该使用i来表示虚数单位,但可能会出现其他符号。
修改之后的代码:
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c;
float delta, root1, root2;
printf("Please enter the three coefficients of a quadratic equation with one variable:\n");
// 对用户输入进行有效性检查
if (scanf("%f %f %f", &a, &b, &c) != 3 || a == 0 || isnan(a) || isnan(b) || isnan(c)) {
printf("Invalid input! Please enter valid coefficients.\n");
return 1;
}
delta = b * b - 4 * a * c;
if (delta > 0) {
root1 = (-b + sqrt(delta)) / (2 * a);
root2 = (-b - sqrt(delta)) / (2 * a);
printf("This equation has two real roots: %.2f and %.2f\n", root1, root2);
} else if (delta == 0) {
root1 = root2 = -b / (2 * a);
printf("This equation has one real root: %.2f\n", root1);
} else {
float realPart = -b / (2 * a);
float imagPart = sqrt(-delta);
printf("This equation has two complex roots: %.2f+%.2fi and %.2f-%.2fi\n", realPart, imagPart, realPart, imagPart);
}
return 0;
}
这样修改之后程序执行会更加安全。