用C语言解决以下问题:1.求方程ax2+bx+c=0的根,用三个子函数分别求当:b2-4ac大于0、等于0和小于0时的根并输出结果,从主函数输入a,b,,c的值。
时间: 2023-11-29 15:01:51 浏览: 200
C语言二分法求解方程根的两种方法
5星 · 资源好评率100%
好的,以下是使用C语言解决该问题的代码:
```c
#include <stdio.h>
#include <math.h>
void roots_greater_than_zero(float a, float b, float c);
void roots_equal_to_zero(float a, float b, float c);
void roots_less_than_zero(float a, float b, float c);
int main()
{
float a, b, c;
printf("Enter values of a, b, c: ");
scanf("%f%f%f", &a, &b, &c);
float D = b * b - 4 * a * c;
if (D > 0)
roots_greater_than_zero(a, b, c);
else if (D == 0)
roots_equal_to_zero(a, b, c);
else
roots_less_than_zero(a, b, c);
return 0;
}
void roots_greater_than_zero(float a, float b, float c)
{
float x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
float x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
printf("Roots are real and different.\n");
printf("x1 = %.2f, x2 = %.2f\n", x1, x2);
}
void roots_equal_to_zero(float a, float b, float c)
{
float x = -b / (2 * a);
printf("Roots are real and equal.\n");
printf("x1 = x2 = %.2f\n", x);
}
void roots_less_than_zero(float a, float b, float c)
{
float realPart = -b / (2 * a);
float imaginaryPart = sqrt(-(b * b - 4 * a * c)) / (2 * a);
printf("Roots are complex and different.\n");
printf("x1 = %.2f + %.2fi, x2 = %.2f - %.2fi\n", realPart, imaginaryPart, realPart, imaginaryPart);
}
```
该代码中,我们定义了三个子函数 `roots_greater_than_zero`、`roots_equal_to_zero` 和 `roots_less_than_zero`,分别用于计算当 $b^2-4ac$ 大于0、等于0和小于0时的根。在主函数中,我们首先读取 $a$、$b$、$c$ 的值,然后计算 $b^2-4ac$ 的值。根据 $b^2-4ac$ 的值,我们调用相应的子函数来计算根,并输出结果。
阅读全文