//用数组实现一元多项的加和乘
#include<iostream>
// #define MaxDegree 100;//注:在这里宏定义之后的还是一个变量。编译器并没有把它当做一个常量。
using namespace std;
const int MaxDegree=100;
typedef struct Node
{
int CoeffArray[MaxDegree+1];
int Highpower;
}*Polynomial;
//把一个多项试设化零
void ZeroPolynomial(Polynomial Poly)
{
for(int i=0;i<=MaxDegree;i++)
{
Poly->CoeffArray[i]=0;//系数设为0
}
Poly->Highpower=0;//最高项次数为0
}
//定义两个多项式的相加
void AddPolynomial(const Polynomial Poly1,const Polynomial Poly2,Polynomial AddPoly)//把不用改变的多项式设为const的
{
cout<<Poly1->Highpower<<" "<<Poly2->Highpower<<" "<<AddPoly->Highpower<<" "<<Poly1<<endl;
ZeroPolynomial(AddPoly);
cout<<Poly1->Highpower<<" "<<Poly2->Highpower<<" "<<AddPoly->Highpower<<" "<<Poly1<<endl;
AddPoly->Highpower=Poly1->Highpower>Poly2->Highpower?Poly1->Highpower:Poly2->Highpower;
cout<<Poly1->Highpower<<" "<<Poly2->Highpower<<" "<<AddPoly->Highpower<<" "<<Poly1<<endl;
// for(int i=0;i<MaxDegree;i++)//注:这样做有一个不足的地方在于要把所有的系数项都相加起来,即使有些地方为空,不需要用的
// {
// Poly->CoeffArray[i]=Poly1->CoeffArray[i]+Poly2->CoeffArray[i];
// }
for(int i=AddPoly->Highpower;i>=0;i--)//从最高项加起就可以避免加一些没有用的项
{
AddPoly->CoeffArray[i]=Poly1->CoeffArray[i]+Poly2->CoeffArray[i];
}
}
//定义两个多项式相乘
void MulPolynomial(const Polynomial Poly1,const Polynomial Poly2,Polynomial MulPoly)
{
ZeroPolynomial(MulPoly);
MulPoly->Highpower=Poly1->Highpower+Poly2->Highpower;
if(MulPoly->Highpower>MaxDegree)
cout<<"Exceeded array size"<<endl;
else
for(int i=0;i<=Poly1->Highpower;i++)
for (int j=0;j<=Poly2->Highpower;j++)
{
MulPoly->CoeffArray[i+j]+=Poly1->CoeffArray[i]*Poly2->CoeffArray[j];
}
}
int main()
{
Polynomial P1,P2,P3,P4;//注:一个很重要的问题,这里是声明了P1他们,而并没有给他们分配内存,在结构体的定义中也没有为他们分配内存。所以在后面要自己审请内存。
// P1=(Polynomial)malloc(sizeof(Polynomial));//审请内存,注这样审请是错的因为这样审只审了一个指针的地址,而并不是想要的数据结构的地址。
P1=(Polynomial)malloc(sizeof(struct Node));
P2=(Polynomial)malloc(sizeof(struct Node));
P3=(Polynomial)malloc(sizeof(struct Node));
P4=(Polynomial)malloc(sizeof(struct Node));
ZeroPolynomial(P1);
ZeroPolynomial(P2);
P1->Highpower=5;
P2->Highpower=8;
cout<<P1->Highpower<<" "<<P2->Highpower<<" "<<P1<<endl;
P1->CoeffArray[0]=9;
P1->CoeffArray[1]=4;
P1->CoeffArray[2]=1;
P1->CoeffArray[3]=2;
P1->CoeffArray[4]=0;
P1->CoeffArray[5]=1;
// P2->CoeffArray[8]={1,0,7,0,0,0,0,0,8};//注:数组的声明与初始化???(没明白)
P2->CoeffArray[0]=1;
P2->CoeffArray[1]=0;
P2->CoeffArray[2]=7;
P2->CoeffArray[3]=0;
P2->CoeffArray[4]=0;
P2->CoeffArray[5]=0;
P2->CoeffArray[6]=0;
P2->CoeffArray[7]=0;
P2->CoeffArray[8]=1;
AddPolynomial(P1,P2,P3);
MulPolynomial(P1,P2,P4);
cout<<P3->Highpower<<endl;
cout<<P4->Highpower<<endl;
return 0;
}
//总结:1 声明与定义的区别重要,声明并没有分配地址而定义给分配了地址
// 2 内存的审请很重要
好好努力,