判断并计算一元二次函数根的情况,在C语言算法设计中是非常简单的。主要依据的就是Δ的正负来判断根的虚实,用Δ的取值来判断根的个数。
代码如下:
//一元二次函数实根和虚根
#include "stdio.h"
#include "math.h"
int main( )
{ float a,b,c,d,x1,x2,lp,ip;
printf("请按顺序输入一元二次函数的二次项系数、一次项系数、常数项系数。\n") ;
scanf("%f%f%f",&a,&b,&c);
printf("the equation ");
if (fabs(a)<1e-6) printf("is not quadratic");
else
{ d=b*b-4*a*c;
if (fabs(d)<=1e-6) /* 相等的实根 */
{ printf("has two equal roots:\n");
printf("x1=x2=%8.4f\n",-b/(2*a));
}
else if (d>1e-6) /* 不相等的实根 */
{ x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("has two real roots:\n") ;
printf("x1=%8.4f, x2=%8.4f\n",x1,x2);
}
else /* 虚根 */
{ lp=-b/(2*a);ip=sqrt(-d)/(2*a);
printf("has two complex roots: \n");
printf("x1=%8.4f+%8.4fi\n",lp,ip);
printf("x2=%8.4f-%8.4fi\n",lp,ip);
}
}
return 0;
}
部分结果如下: