永发信息网

c++用类求解一元二次方程

答案:1  悬赏:50  手机版
解决时间 2021-05-15 09:33
  • 提问者网友:温柔港
  • 2021-05-14 11:54

编写一个类,实现一元二次方程组的求解 要求:(1)类的数据成员和函数成员(包括构造函数)要设计清晰,对它们的访问做好限定;(2)有两个构造函数,其中一个不带参数,另一个带参数,不带参数构造函数初始化a=1,b=2,c=2,类最终实现方程组x*x+2x+2=0的解,带参数的构造函数通过对外接口获得a,b,c,并解方程;(4)main函数调用类实现解方程和输出结果。

我最后编的 有什么问题 请高手指正 谢谢

#include<iostream>
#include<math.h>
using namespace std;
class M
{public:
M();
M(float a,float b,float c):A(a),B(b),C(c){}
float X();
private:
float A;
float B;
float C;
};
M::M()
{
A=1;
B=2;
C=2;
}

float M::X()
{
float a,b,c,d,e,x1,x2;
d=b*b-4*a*c;
if(a=0)
{
x1=x2=-c/b;
cout<<"x="<<x1<<endl;
}
else
{
if(d<0)
{
e=sqrt(d);
x1=-b/(2*a)+e/(2*a);
x2=-b/(2*a)-e/(2*a);
cout<<"x1="<<x1;
cout<<"i"<<endl;
cout<<"x2="<<x2;
cout<<"i"<<endl;
}
if(d==0)
{
cout<<"There is only x."<<endl;
x1=x2=(-b)/(2*a);
cout<<"x1=x2="<<x1<<endl;
}
if(d>0)
{
e=sqrt(d);
x1=(-b+e)/(2*a);
x2=(-b-e)/(2*a);
cout<<"x1="<<x1<<endl;
cout<<"x2="<<x2<<endl;
}
}
return(x1,x2);
}
int main()
{
cout<<"a=1,b=2,c=2"<<endl;
M m1;
m1.X();
M m2;
float a,b,c;
cout<<"a: ";
cin>>a;
cout<<"b: ";
cin>>b;
cout<<"c: ";
cin>>c;
m2.X();
return 0;
}

最佳答案
  • 五星知识达人网友:青灯有味
  • 2021-05-14 13:19

#include<iostream>
#include<math.h>
using namespace std;
class M
{public:
M();
M1(float a,float b,float c);
M(float a,float b,float c){}
float X();
public:
float A;
float B;
float C;
};
M::M()
{
A=1;
B=2;
C=2;
}


M::M1(float a,float b,float c){
A = a;
B = b;
C = c;
}


float M::X()
{
cout<<"A="<<A;
cout<<"B="<<B;
cout<<"C="<<C<<endl;
float d,e,x1,x2;
d=B*B-4*A*C;
cout<<"d="<<d<<endl;
if(A==0)
{
x1=x2=-C/B;
cout<<"x="<<x1<<endl;
}
else
{
if(d<0)
{
e=sqrt(d);
cout<<"e1="<<e<<endl;
x1=-B/(2*A)+e/(2*A);
x2=-B/(2*A)-e/(2*A);
cout<<"x1="<<x1;
cout<<"i"<<endl;
cout<<"x2="<<x2;
cout<<"i"<<endl;
}
if(d==0)
{
cout<<"There is only x."<<endl;
x1=x2=(-B)/(2*A);
cout<<"x1=x2="<<x1<<endl;
}
if(d>0)
{
e=sqrt(d);
cout<<"A="<<A;
cout<<"B="<<B;
cout<<"C="<<C<<endl;
cout<<"e2="<<e<<endl;
x1=(-B+e)/(2*A);
x2=(-B-e)/(2*A);
cout<<-B+e<<endl;
cout<<2*A<<endl;
cout<<-B-e<<endl;
cout<<"x1="<<x1<<endl;
cout<<"x2="<<x2<<endl;
}
}
return(x1,x2);
}
int main()
{
cout<<"a=1,b=2,c=2"<<endl;
M m1;
m1.X();
M m2;
float a,b,c;
cout<<"a: ";
cin>>a;
cout<<"b: ";
cin>>b;
cout<<"c: ";
cin>>c;
m2.M1(a,b,c);
m2.X();
return 0;
}


这是在你的程序上修改后的程序,你对比下看看吧

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯