用C语言计算一元二次方程的根
时间: 2024-11-23 21:27:25 浏览: 14
在C语言中,计算一元二次方程的根通常涉及到求解一般形式的二次方程 ax² + bx + c = 0。我们可以使用公式法来求解,公式是:
\[ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \]
以下是简单的C程序示例,它包含一个函数`quadratic_solver`用于计算二次方程的两个根:
```c
#include <stdio.h>
#include <math.h>
void quadratic_solver(double a, double b, double c) {
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double root1 = (-b + sqrt(discriminant)) / (2 * a);
double root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and distinct: %.2lf and %.2lf\n", root1, root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
printf("Root is real and repeated: %.2lf\n", root);
} else {
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex conjugates: %.2lf + %.2lfi and %.2lf - %.2lfi\n",
realPart, imaginaryPart, realPart, imaginaryPart);
}
}
int main() {
double a, b, c;
printf("Enter coefficients a, b, and c for the equation ax² + bx + c = 0: ");
scanf("%lf %lf %lf", &a, &b, &c);
quadratic_solver(a, b, c);
return 0;
}
```
阅读全文