class polynomial
{
int *a;
int power;
public:
polynomial(int n)
{
power = n;
a = new int[n+1];
for(int i=0;i<=n;i++)
{
a[i] = 0;
}
}
polynomial(int aa[], int n)
{
power = n;
a = new int[n+1];
for(int i=0;i<=n;i++)
{
a[i] = aa[i];
}
}
polynomial(const polynomial &p)
{
power = p.power;
a = new int[power];
for(int i=0;i<=power;i++)
{
a[i] = p.a[i];
}
}
~polynomial()
{
delete []a;
}
void show()
{
for(int i=0;i<=power;i++)
{
if(i==0)
{
cout<<a[i]<<"+";
}
else if(i==power)
{
cout<<a[i]<<"x^"<<i;
}
else
{
cout<<a[i]<<"x^"<<i<<"+";
}
}
cout<<endl;
}
polynomial operator+(const polynomial &p)
{
polynomial p0(power>p.power?power:p.power);
if(power>p.power)
{
for(int i=0;i<=p.power;i++)
{
p0.a[i] = a[i] + p.a[i];
}
for(int i=p.power+1;i<=power;i++)
{
p0.a[i] = a[i];
}
}
else
{
for(int i=0;i<=power;i++)
{
p0.a[i] = a[i] + p.a[i];
}
for(int i=power+1;i<=p.power;i++)
{
p0.a[i] = p.a[i];
}
}
return p0;
}
};
int main()
{
int a[] = {1,3,5,7,5,5};
polynomial p1(a,5);
p1.show();
polynomial p2(p1);
p2.show();
int b[] = {4,6,6};
polynomial p3(b,2);
p3.show();
polynomial p4 = p3+p2;
p4.show();
}
多项式类的构造
最新推荐文章于 2024-11-08 23:39:16 发布