C语言:一元二次方程解的所有情况
从键盘任意输入a,b,c的值,编程计算并输出一元二次方程ax2+bx+c=0的根,当a=0时,输出“该方程不是一元二次方程”,当a≠0时,分b2−4ac>0、b2−4ac=0、b2−4ac<0三种情况计算并输出方程的根。
**输入格式要求:"%f,%f,%f" 提示信息:"Please enter the coefficients a,b,c:"
**输出格式要求:"It is not a quadratic equation!\n" "x1 = x2 = %.2f\n" "x1 = %.2f, x2 = %.2f\n"
"x1 = %.2f+%.2fi, " "x2 = %.2f-%.2fi\n"
程序运行示例1如下:
Please enter the coefficients a,b,c:0,10,2
It is not a quadratic equation!
程序运行示例2如下:
Please enter the coefficients a,b,c:1,2,1
x1 = x2 = -1.00
程序运行示例3如下:
Please enter the coefficients a,b,c:2,3,2
x1 = -0.75+0.66i, x2 = -0.75-0.66i
变量定义为float类型,精度要求为1e-6,即
#define EPS 1e-6
1 #include<stdio.h> 2 #include<math.h> 3 #define EPS 1e-6 4 main() { 5 float a, b, c, d, x1, x2, i; 6 printf("Please enter the coefficients a,b,c:"); 7 scanf("%f,%f,%f", &a, &b, &c); 8 d = b * b - 4 * a * c; 9 if (fabs(a)<=0) 10 printf("It is not a quadratic equation!\n"); 11 else 12 { 13 if (d<0) 14 { 15 x1 = -b / (2 * a); 16 i = sqrt(-d) / (2 * a); 17 printf("x1 = %.2f+%.2fi," , x1, i); 18 printf("x2 = %.2f-%.2fi\n" , x1, i); 19 } 20 else if (fabs(d) > EPS) 21 { 22 x1 = (-b + sqrt(d)) / (2 * a); 23 x2 = (-b - sqrt(d)) / (2 * a); 24 printf("x1 = %.2f, x2 = %.2f\n", x1, x2); 25 } 26 else if (fabs(d)<=EPS) 27 printf("x1 = x2 = %.2f\n", -b / (2 * a)); 28 } 29 30 }