求方程ax2+bx+c=0的根,用3个函数分别求当b2-4ac>0、b2-4ac=0、b2-4ac<0时的根,并输出结果。从主函数输入a,b,c的值。
- 代码如下:
#include<stdio.h>
#include<math.h>
double x1,x2,flag,p,q;
void greater(double a,double b);
void equal(double a,double b);
void smaller(double a,double b);
int main()
{
double a,b,c;
printf("Input a,b,c:");
scanf("%lf%lf%lf",&a,&b,&c);
greater(a,b);
equal(a,b);
smaller(a,b);
flag=b*b-4*a*c;
printf("equation:%.2lf*x*x+%.2lf*x+%.2lf=0\n",a,b,c);
if(flag>0){
greater(a,b);
printf("x1=%lf x2=%lf\n",x1,x2);
}
if(flag==0){
equal(a,b);
printf("x1=%lf x2=%lf\n",x1,x2);
}
if(flag<0){
smaller(a,b);
printf("x1=%lf+%lfi,x2=%lf-%lfi\n",p,q,p,q);
}
return 0;
}
void greater(double a,double b)
{
x1=(-b+sqrt(flag))/(2*a);
x2=(-b-sqrt(flag))/(2*a);
}
void equal(double a,double b)
{
x1=x2=(-b)/(2*a);
}
void smaller(double a,double b)
{
p=(-b)/(2*a);
q=sqrt(-flag)/(2*a);
}
运行结果如下:
两个不相等的实根:
两个相等的实根:
两个共轭复根: