如何用C++求解方程ax^2+bx+c=0的解

2025-04-02 14:24:37
推荐回答(4个)
回答1:

#include
#include
class Equation{
float a,b,c;

public:
float x[2];
Equation(float a1=0.0,float b1=0.0,float c1=0.0)
{
a=a1;
b=b1;
c=c1;
}
~Equation(){}
long CalResult();

};
long Equation::CalResult()
{
long temp;
if ((b*b-4*a*c)==0)
{
temp=1;
x[0]=(float)(-(b/2*a));
return temp;
}
if ((b*b-4*a*c)>0)
{
temp=2;
x[0]=(-b+sqrt(b*b-4*a*c))/(2*a);
x[1]=(-b-sqrt(b*b-4*a*c))/(2*a);
return temp;
}
else
{
temp=0;
}
return temp;
}

int main()
{
float a,b,c;
char ch;
do{
cout<<"请输入一元二次方程系数a"< cin>>a;
cout<<"请输入一元二次方程系数b"< cin>>b;
cout<<"请输入一元二次方程系数c"< cin>>c;
Equation *obj=new Equation(a,b,c);
cout<<"方程有"<CalResult()<<"个根"< if (obj->CalResult()==1)
{
cout<<"X="<x[0]< }
if (obj->CalResult()==2)
{
cout<<"X1="<x[0]< cout<<"X2="<x[1]< }
delete obj;
cout<<"是否继续计算?(1)"< cin>>ch;
}while(ch=='1');

return 0;
}

回答2:

#include

#include
int f(double a,double b,double c,double *x1,double *x2)
{
double d=b*b-4*a*c;
if(d>0)
{
*x1=(-b+sqrt(d))/(2*a);
*x2=(-b-sqrt(d))/(2*a);
return 1;
}
else if(d==0)
{
*x1=*x2=(-b)/(2*a);
return 0;
}
else
return -1;
}
void main()
{ double a1,a2,a3,y1,y2,t;
printf("请输入要解方程的系数:\n");
scanf("%lf%lf%lf",&a1,&a2,&a3);
t=f(a1,a2,a3,&y1,&y2);
if(t>0)
printf("x1=%.10f tx2=%.10f\n",y1,y2);
else if(t==0)
printf("x1=x2=%.4f\n",y1);
else printf("此方程无解!");

}

回答3:

同意一下的

回答4:

dfs