用c语言编写程序求ax 2 +bx+c=0方程的根,其中a,b,c从键盘输入
时间: 2023-05-30 09:04:13 浏览: 411
c代码-求ax平方+bx+c+=0
5星 · 资源好评率100%
```
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, discriminant, root1, root2;
printf("Enter coefficients a, b, c: ");
scanf("%f %f %f", &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("Roots are real and different.\n");
printf("Root1 = %.2f and Root2 = %.2f", root1, root2);
} else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("Roots are real and same.\n");
printf("Root1 = Root2 = %.2f", root1);
} else {
float realPart = -b / (2 * a);
float imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and different.\n");
printf("Root1 = %.2f + %.2fi and Root2 = %.2f - %.2fi", realPart, imaginaryPart, realPart, imaginaryPart);
}
return 0;
}
```
注:%.2f表示保留两位小数输出。
阅读全文