c++求解:定义一元二次方程类,数据成员为私有,求方程的根(虚根实根都要)

2024-12-19 12:35:53
推荐回答(3个)
回答1:

#include
#include

class LQuadEqu
{
double a,b,c; //方程为 aX^2+bX+c=0
double ReA,ImA; //存第一个根的实部ReA, 和虚部ImA
double ReB,ImB; //存第2个根的实部和虚部
int rt; //rt=2有不等实根,rt=-2有不等虚根,rt=1有相等实根
public:
LQuadEqu(double aa,double bb, double cc);

//getResult用来取得方程的根,输入参数为指向存放各根的变量的指针,传指针是为了改值
//返回值为根的数目和类型 2有不等实根,-2有不等虚根,1有相等实根
int getResult(double *pReA, double *pImA, double *pReB, double *pImB);
};
LQuadEqu::LQuadEqu(double aa,double bb,double cc)
{
a=aa;b=bb;c=cc;

//计算公式为X=(-b+sqrt(b*b-4ac))/2/a和(-b-sqrt(b*b-4ac))/2/a
double tmp;
tmp = b*b-4*a*c;
if(tmp<0)
{ //有不等虚根
rt=-2;
ReA = ReB = -b/2.0/a;
ImA = sqrt(-tmp)/2.0/a;
ImB = -ImA;
}
else if(tmp>0)
{ //有不等实根
rt=2;
ImA=ImB=0;
ReA=(-b+sqrt(tmp))/2.0/a;
ReB=(-b-sqrt(tmp))/2.0/a;
}
else
{ //tmp==0 有相等实根
rt=1;
ImA=ImB=0;
ReA=ReB=-b/2.0/a;
}
}
int LQuadEqu::getResult(double *pReA, double *pImA, double *pReB, double *pImB)
{
*pReA=ReA; *pImA=ImA; *pReB=ReB; *pImB=ImB;
return rt;
}

void main ( )
{
double a,b,c,reA,imA,reB,imB;
int r;
printf("输入二次方程的参数a b c\n");
scanf("%lf%lf%lf",&a,&b,&c);
printf("方程%f X^2 + %f X + %f\n",a,b,c);
LQuadEqu lqe(a,b,c); //生成,计算
r = lqe.getResult(&reA,&imA,&reB,&imB); //取结果
if( r==2 )
printf("有两个不相等实根 %f %f\n",reA,reB);
else if( r==-2 )
printf("有两个不相等虚根 (%f,%fi) (%f,%fi)\n",reA,imA,reB,imB);
else
printf("有两个相等实根 %f\n",reA);
getchar(); //使用者按任意键结束
}

回答2:

楼上手真快!
#include
#include
using namespace std;

class OneTwo
{
public:
OneTwo(double ia,double ib,double ic):a(ia),b(ib),c(ic){}
void printAnswer();
private:
double a;
double b;
double c;
};

void OneTwo::printAnswer()
{
if(a==0)
{
if(b!=0)
cout<<"只有一个解:\n"<<"x="<<-c/b< else
cout<<"error!\n"<<"无解"< }
else
{
double delta=b*b-4*a*c;
double sqDelta=sqrt(fabs(delta));
if(delta<0)
cout<<"解为虚数:\n"<<"x1="<<-b/(2*a)<<"+"< <<"x2="<<-b/(2*a)<<"-"< else
{
if(delta==0)
cout<<"有两个相同的解:\n"<<"x1=x2="<<-b/(2*a)< else
cout<<"有两个不同的解:\n"<<"x1="<<-b/(2*a)+sqDelta/(2*a)<<"\n"//两个不同的实根
<<"x2="<<-b/(2*a)-sqDelta/(2*a)< }
}
}

int main()
{
OneTwo F(1,5,1);//初始化F
F.printAnswer();//打印出解
return 0;
}

回答3:

不懂。。。。。。。。