请高手帮忙看看,多谢了!
是关于多项式的加减的一个算法。我调试了半天,实现加法没问题了,可是减法实现老是出问题。请高手们指点一下!不胜感激!以下是程序:
#include "stdafx.h"
#include<iostream>
using namespace std;
struct term
{
float coef;//项的指数
int expn;//项的指数
term *next;
};
term *creatpolyn(int m)//输入并建立一元多项式
{
if(m<=0)
{
return NULL;
}
term *head=NULL;
term *p=new term;
term *pre=NULL;
int i;
cout<<"依次输入m个非零项,[多项式的每一项用两个数字表示(前一个数字代表系数,后一个数字代表指数)]"<<endl;
for(i=0;i<m;i++)
{
if (head==NULL)
{
cin>>p->coef>>p->expn;
head=p;
pre=head;
}
else
{
p=pre->next=new term;
cin>>p->coef>>p->expn;
pre=p;
}
}
pre->next=NULL;
return head;
}
term *deal(term *h)//对多项式进行处理(排序,合并同指数项,消去系数为0项)
{
if(h==NULL)
{
return NULL;
}
term *g=NULL;
term *p=NULL;
term *q=NULL;
float f;
int k;
bool flag=true;
for(g=h; (g->next!=NULL)&&flag; g=g->next)//排序
{
flag=false;
for(p=h,q=p->next; q!=NULL; p=p->next,q=q->next)
{
if(p->expn<q->expn)
{
f=p->coef;k=p->expn;
p->coef=q->coef;p->expn=q->expn;
q->coef=f;q->expn=k;
flag=true;
}
}
}
for(g=h,p=g->next; p!=NULL;)//合并同指数项
{
if(g->expn!=p->expn)
{
g=p;
p=g->next;
}
else
{
g->coef=g->coef+p->coef;
g->next=p->next;
q=p;
p=p->next;
delete q;
}
}
g=h;//消去系数为0项
while (g!=NULL)
{
if (g->coef!=0)
{
q=g;
g=q->next;
}
else
{
q=g;
g=q->next;
delete q;
}
}
return h;
}
term *addpolyn(term *p1,term *p2)//加法
{
term *g1=p1;
while (g1->next!=NULL)
{
g1=g1->next;
}
g1->next=p2->next;
g1->next=p2;
p1=deal(p1);
return p1;
}
term *subractpolyn(term *p1,term *p2)//减法
{
term *p3=p2;
while (p3!=NULL)
{
p3->coef=0-p3->coef;
p3=p3->next;
}
term *p=addpolyn(p1,p2);
return p;
}
void printfpolyn(term *h)//输出多项式
{
term *p=h;
if (h==NULL)
{
cout<<'0'<<endl;
}
else
{
while(p->next!=NULL)
{
if (p->next->coef>=0)
{
cout<<p->coef<<"X^"<<p->expn<<"+";
}
else
{
cout<<p->coef<<"X^"<<p->expn;
}
p=p->next;
}
cout<<p->coef<<"X^"<<p->expn<<endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int m;
int n;
char g;
term *p1=NULL;
term *p2=NULL;
term *p=NULL;
cout<<"输入要建立的多项式的项数m"<<endl;
cin>>m;
p1=creatpolyn(m);
cout<<"得到多项式1"<<endl;
printfpolyn(p1);
cout<<"输入另一多项式的项数n"<<endl;
cin>>n;
p2=creatpolyn(n);
cout<<"得到多项式2"<<endl;
printfpolyn(p2);
cout<<"请选择要进行的运算,如要相加则输入+,如要相减则输入-"<<endl;
cin>>g;
switch (g)
{
case '+':p=addpolyn(p1,p2);
break;
case '-':p=subractpolyn(p1,p2);
break;
}
cout<<"结果如下"<<endl;
printfpolyn(p);
return 0;
}