c语言求方程ax²+bx+c=0的根,用3个函数分别求当:b²-4ac大于0,等于0,小于0时的根并输出结果。从主函数输入a,b,c的值
时间: 2024-06-13 18:08:08 浏览: 139
c代码-求ax平方+bx+c+=0
以下是C语言求解一元二次方程的程序,其中包括三个函数分别求当b²-4ac大于0,等于0,小于0时的根并输出结果。从主函数输入a,b,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("Please enter the value of a, b, c:\n");
scanf("%f%f%f", &a, &b, &c);
float discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
roots_greater_than_zero(a, b, discriminant);
} else if (discriminant == 0) {
roots_equal_to_zero(a, b);
} else {
roots_less_than_zero(a, b, discriminant);
}
return 0;
}
void roots_greater_than_zero(float a, float b, float discriminant) {
float root1 = (-b + sqrt(discriminant)) / (2 * a);
float root2 = (-b - sqrt(discriminant)) / (2 * a); printf("The roots are real and different.\n");
printf("root1 = %.2f, root2 = %.2f\n", root1, root2);
}
void roots_equal_to_zero(float a, float b) {
float root = -b / (2 * a);
printf("The roots are real and equal.\n");
printf("root1 = root2 = %.2f\n", root);
}
void roots_less_than_zero(float a, float b, float discriminant) {
float realPart = -b / (2 * a);
float imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("The roots are complex and different.\n");
printf("root1 = %.2f + %.2fi, root2 = %.2f - %.2fi\n", realPart, imaginaryPart, realPart, imaginaryPart);
}
```
阅读全文