用c语言形成一段解一元二次方程的代码
时间: 2024-11-06 19:15:03 浏览: 56
在C语言中,解一元二次方程通常涉及公式 `x = [-b ± sqrt(b^2 - 4ac)] / 2a`,如果判别式 `b^2 - 4ac` 大于0,则有两个实根;小于0则无实根,等于0则有一个实根。这里是一个简单的例子,使用了 `math.h` 库来进行数学运算:
```c
#include <stdio.h>
#include <math.h>
// 定义函数来解一元二次方程
double 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("方程有两解:x1 = %.2lf, x2 = %.2lf\n", root1, root2);
} else if (discriminant == 0) {
// 只有一个实根
double root = -b / (2 * a);
printf("方程有一个解:x = %.2lf\n", root);
} else {
// 无实根
printf("方程无实根\n");
}
}
int main() {
double a, b, c;
printf("请输入一元二次方程的系数(a, b, c): ");
scanf("%lf %lf %lf",
阅读全文
相关推荐


















