求方程ax2+bx+c=0的根,用三个函数分别求当b2-4ac>0,等于0和小于0的根并输出结果.从主函数输入a,b,c的值
来源:学生作业帮助网 编辑:六六作业网 时间:2025/02/03 17:16:39
求方程ax2+bx+c=0的根,用三个函数分别求当b2-4ac>0,等于0和小于0的根并输出结果.从主函数输入a,b,c的值
求方程ax2+bx+c=0的根,用三个函数分别求当b2-4ac>0,等于0和小于0的根并输出结果.从主函数输入a,b,c的值
求方程ax2+bx+c=0的根,用三个函数分别求当b2-4ac>0,等于0和小于0的根并输出结果.从主函数输入a,b,c的值
#include
#include
#include
int Judge( double a,double b,double c)
{
double result = b*b - 4*a*c;
if( result == 0 )
return 0;
else if( result > 0 )
return 1;
else
return -1;
}
void ComputeGreatThanZero( double a,double b,double c )
{
printf( "x1 = %gf,x2 = %gf",(-b+sqrt(b*b-4*a*c))/(2*a),((-b-sqrt(b*b-4*a*c))/(2*a)) );
}
void ComputeEqualZero( double a,double b ,double c )
{
printf( "x1 = x2 = %g",-b/(2*a));
}
void ComputeBelowZero( double a,double b,double c )
{
double delta = sqrt(4*a*c-b*b);
double temp = delta/(2*a);
printf( "x1 = %g ",-b/(2*a));
if( temp > 0 )
printf( " + %gi,",temp);
else
printf( " - %gi,",fabs(temp) );
printf( "x2 = %g",-b/(2*a) );
if( delta > 0 )
printf( " - %gi",fabs( temp));
else
printf( " + %gi",fabs(temp));
}
void main()
{
double a,b,c;
int flag;
scanf( "%lf%lf%lf",&a,&b,&c);
if( a == 0 )
{
printf( "\n a = 0\n");
exit(1);
}
flag = Judge( a,b,c);
if( flag > 0 )
ComputeGreatThanZero(a,b,c);
else if( flag == 0 )
ComputeEqualZero(a,b,c);
else
ComputeBelowZero(a,b,c);
}
// zd_44.cpp :Defines the entry point for the console application.
//
#include
#include
float x1,x2,disc,p,q;
greater_than_zero(float a,float b)
{
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
}
equal_to_zero(float a,float b)
{
x1=x2=(-b)/(2*a);
}
smaller_than_zero(float a,float b)
{
p=-b/(2*a);
q=sqrt(abs(disc))/(2*a);
}
int main(int argc,char* argv[])
{
float a,b,c;
printf("Input a,b,c:");
scanf("%f,%f,%f",&a,&b,&c);
printf("\nequation:%5.2f*x*x+%5.2f*x+%5.2f=0\n",a,b,c);
disc=b*b-4*a*c;
printf("root:\n");
if(disc>0)
{
greater_than_zero(a,b);
printf("x1=%5.2f\tx2=%5.2f\n\n",x1,x2);
}
else if(disc==0)
{
equal_to_zero(a,b);
printf("x1=%5.2f\tx2=%5.2f\n\n",x1,x2);
}
else
{
smaller_than_zero(a,b);
printf("x1=%5.2f+%5.2fi\tx2=%5.2f-%f5.2i\n",p,q,p,q);
}
printf("Hello World!\n");
return 0;
}
运行结果:
Input a,b,c:7,4,3
equation:7.00*x*x+ 4.00*x+ 3.00=0
root:
x1=-0.29+ 0.59i x2=-0.29-0.5890155.2i
Hello World!
Press any key to continue