用C++写程序:求方程ax^2+bx+c=0的根,用3个函数分别求当b^2-4ac大于0,等于0和小于0时的根,并输出结果

从主函数输入a,b,c的值
2025-02-27 14:26:25
推荐回答(3个)
回答1:

#include
#include
using namespace std;
float x1,x2,disc,p,q;
int main()
{void greater_than_zero(float,float);
void equal_to_zero(float,float);
void smaller_than_zero(float,float);
float a,b,c;
cout<<"input a,b,c:";
cin>>a>>b>>c;
disc=b*b-4*a*c;
cout<<"root:"< if (disc>0)
{
greater_than_zero(a,b);
cout<<"x1="< }
else if (disc==0)
{equal_to_zero(a,b);
cout<<"x1="< }
else
{smaller_than_zero(a,b);
cout<<"x1="< cout<<"x2="< }
return 0;
}

void greater_than_zero(float a,float b) /* 定义一个函数,用来求disc>0时方程的根 */
{x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
}

void equal_to_zero(float a,float b) /* 定义一个函数,用来求disc=0时方程的根 */
{
x1=x2=(-b)/(2*a);
}

void smaller_than_zero(float a,float b) /* 定义一个函数,用来求disc<0时方程的根 */
{
p=-b/(2*a);
q=sqrt(-disc)/(2*a);
}

回答2:

#include
#include
using namespace std;
float x1,x2,disc,p,q;
int main()
{void greater_than_zero(float,float);
void equal_to_zero(float,float);
void smaller_than_zero(float,float);
float a,b,c;
cout<<"input a,b,c:";
cin>>a>>b>>c;
disc=b*b-4*a*c;
cout<<"root:"< if(disc>0)
{greater_than_zero(a,b);
cout<<"x1="< }
else if(disc==0)
{equal_to_zero(a,b);
cout<<"x1="< }
else
{small_than_zero(a,b);
cout<<"x1="< cout<<"x2="< }
return 0;
}

void greater_than_zero(float a,float b)
{x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
}

void equal_to_zero(floata,float b)
{x1=x2=(-b)/(2*a);
}

void smaller_than_zero(float a,float b)
{p=-b/(2*a);
q=sqrt(-disc)/(2*a);
}

回答3:

#include
#include
float e,f,g,h,i;
int main()
{
float yishigen(float x,float y);
float denggen(float x);
float xugen();
float a,b,c,p,q,k;
scanf("%f,%f,%f",&a,&b,&c);
p=-b/(2*a);
q=b*b-4*a*c;
k=sqrt(q)/(2*a);
if(q>0)
{
yishigen(p+k,p-k);
printf("x1=%f,x2=%f",p+k,p-k);
}

else if(q==0)
{
denggen(p);
printf("x1=x2=%f",p);
}
else
{
xugen();
printf("No!");
}

}
float yishigen(float x,float y)
{
h=-f/(2*e);
i=sqrt(e*e-4*e*f);
x=h+i;
y=h-i;
}
float denggen(float x)
{
h=-f/(2*e);
x=h;
}
float xugen()
{
printf("No!");
}当然IF(Q <0),你可以用虚数求解,但我觉得直接输出No!就好了!