C 编程:求解二次方程根的程序
要理解这个示例,你应该具备以下C语言编程相关知识:
二次方程的标准形式是:
ax2 + bx + c = 0,其中
a、b 和 c 是实数且
a != 0
术语 b2 - 4ac
被称为二次方程的判别式。它决定了根的性质。
- 如果判别式大于
0
,则根是实数且不同。 - 如果判别式等于
0
,则根是实数且相等。 - 如果判别式小于
0
,则根是复数且不同。
程序求解二次方程的根
#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &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("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// 实数且根相同的情况
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// 根不是实数的情况
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart);
}
return 0;
}
输出
Enter coefficients a, b and c: 2.3
4
5.6
root1 = -0.87+1.30i and root2 = -0.87-1.30i