#include"iostream" #include"stdio.h" #include"string.h" #include"algorithm" #include"queue" #include"stack" #include"ctype.h" #include"cmath" #define mx 1005 using namespace std; struct poly //链表节点数据类型 { double ceof;//系数 int exp;//指数 poly *next; }; double A[mx],B[mx];//存放A和B表达式 int adegree,bdegree,maxexp;//存放最高阶数 void init(poly *&pl) //链表初始化 { pl=new poly;//动态分配空间,如果出现错误则输出 allocate error if(pl==NULL){cout<<"allocate error!"<<endl;} else { pl->next=NULL; } } void input(poly *&pl,int degree,double X[]) //表达式的输入(存入链表中) { poly *t=pl; int i=0; while(i<=degree) { if(X[i]!=0) //系数为零的不用存 { t->next=new poly; t=t->next; t->ceof=X[i]; t->exp=i; } i++; } t->next=NULL; } void output(poly *&pl) //表达式的输出 { poly *t=pl->next; cout<<"the polynomal is:"; bool h=true; while(t!=NULL) { if(!h) cout<<"+"; h=false; if(t->ceof!=1||t->exp==0) cout<<t->ceof; switch(t->exp) //根据阶数输出相应的项 { case 0:break; case 1:cout<<"x";break; default:cout<<"x^"<<t->exp; } t=t->next; } cout<<endl; } void insert_poly(poly *&pl,double ceof_,int exp_) { poly *t,*pre,*newpoly; t=pl->next;pre=pl; while(t!=NULL&&t->exp>exp_) { pre=t; t=t->next; } if(t!=NULL&&t->exp==exp_) { t->ceof+=ceof_; if(t->ceof==0)//如果多项式系数为零,则删除 { pre->next=t->next; delete t; } } else { newpoly=new poly; newpoly->ceof=ceof_; newpoly->exp=exp_; pre->next=newpoly; newpoly->next=t; } } void mul_poly(poly *&pla,poly *&plb,poly *&plc) //用插入法实现表达式相乘 { poly *ta,*tb; if(adegree!=-1&&bdegree!=-1) //没有零多项式,执行相乘运算 { ta=pla->next; while(ta!=NULL)//模拟笔算多项式相乘 { tb=plb->next; while(tb!=NULL) { insert_poly(plc,(ta->ceof)*(tb->ceof),ta->exp+tb->exp); tb=tb->next; } ta=ta->next; } } } int main() { poly *pla,*plb,*plc; int i,j,_exp; double _ceof; char ch; int case_=0; while(++case_) { cout<<"case "<<case_<<":"<<endl; memset(A,0,sizeof(A)); memset(B,0,sizeof(B)); init(pla);//初始化,这个操作一定要有 init(plb); init(plc); ch=‘0‘; cout<<"input A poly:"; while(ch!=‘\n‘)//A表达式的输入 { cin>>_ceof; getchar();getchar(); cin>>_exp; ch=getchar(); A[_exp]=_ceof; adegree=_exp; } input(pla,adegree,A); cout<<"input B poly:"; ch=‘0‘; while(ch!=‘\n‘)//B表达式的输入 { cin>>_ceof; getchar();getchar(); cin>>_exp; ch=getchar(); B[_exp]=_ceof; bdegree=_exp; } input(plb,bdegree,B); mul_poly(pla,plb,plc); output(plc);//输出最终结果 cout<<"insert one formula to the poly:"; cin>>_ceof; getchar();getchar(); cin>>_exp; insert_poly(plc,_ceof,_exp); output(plc);//输出插入一项后的最终结果 cout<<endl; } }
时间: 2024-10-06 04:26:31