一、题目
求方程ax2+bx+c=0的根,用3个函数分别求当:bx2-4ac大于0、等于0和小于0时的根并输出结果。从主函数输入a,b,c的值。
二、代码及结果
1.代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float x1,x2,t,p,q;
int main()
{
void Greater_than_Zero(float a,float b);
void Equal_to_Zero(float a,float b);
void Smaller_than_zero(float a,float b);
float a,b,c;
printf("请输入a,b,c的值:\n");
scanf("%f,%f,%f",&a,&b,&c);
printf("解方程:%4.2f*x*x+%4.2f*x+%4.2f=0\n",a,b,c);
t=b*b-4*a*c;
if(t>0)
{
Greater_than_Zero(a,b);
printf("x1=%f\nx2=%f\n",x1,x2);
}
else if(t==0)
{
Equal_to_Zero(a,b);
printf("x1=x2=%f\n",x1);
}
else
{
Smaller_than_zero(a,b);
printf("x1=%f+%fi\nx2=%f-%fi\n",p,q,p,q);
}
return 0;
}
void Greater_than_Zero(float a,float b)
{
x1=(-b+sqrt(t))/(2*a);
x2=(-b+sqrt(t))/(2*a);
}
void Equal_to_Zero(float a,float b)
{
x1=x2=(-b)/(2*a);
}
void Smaller_than_zero(float a,float b)
{
p=-b/(2*a);
q=sqrt(-t)/(2*a);
}