一元多项式计算
1,能够按照指数和升序排列建立并输出多项式!
2,能够完成两个多项式的加法,减法,乘法,并将结果存储与一个新的多项式中!
#include <list>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
class _Item: public pair < int,int >
{
public:
_Item(): pair < int,int > (int(),int()){}
_Item(int a,int b): pair < int,int > (a,b){}
_Item(const _Item &rhs): pair < int,int > (rhs.first,rhs.second){}
inline bool operator < (const _Item &other)const
{
return second < other.second;
}
inline bool operator==(const _Item &other)const
{
return second==other.second;
}
inline bool operator > (const _Item &other)const
{
return second > other.second;
}
inline void operator+=(const _Item &other)
{
first+=other.first;
}
inline void operator-=(const _Item &other)
{
first-=other.first;
}
inline void operator*=(const _Item &other)
{
first*=other.first;
second+=other.second;
}
void operator=(const _Item &other)
{
first=other.first;
second=other.second;
}
friend istream &operator>>(istream &is,_Item &it)
{
is>>it.first>>it.second;
return is;
}
friend ostream &operator<<(ostream &os,const _Item &it)
{
if(it.first > 0)
os<<"+";
os<<it.first<<"x^"<<it.second;
return os;
}
};
class EqualZero
{
public:
inline bool operator()(const _Item &it)const
{
return it.first==0;
}
};
typedef list < _Item > List;
typedef List::iterator iList;
void InputList(List &la)
{
la.clear();
cout<<"请依次输入基数和指数(空格分割)回车转下一组\n..以都为0结束."<<endl;
iList il;
_Item temp;
cin>>temp;
temp;
while(temp.first!=0||temp.second!=0)
{
if(la.end()!=(il=find(la.begin(),la.end(),temp)))
{
*il+=temp;
}
else
{
la.push_back(temp);
}
cin>>temp;
}
la.remove_if(EqualZero());
la.sort();
}
void ShowList(List &la)
{
if(la.empty())
return ;
iList il=la.begin();
cout<<il->first<<"x^"<<il->second;
++il;
while(il!=la.end())
{
cout<< *il;
++il;
}
cout<<endl;
}
List AddList(List &la,List &lb)
{
if(la.empty())
return lb;
else if(lb.empty())
return la;
List lc(la);
iList ilb,ilc;
for(ilb=lb.begin();ilb!=lb.end();++ilb)
{
ilc=lc.begin();
while(ilc!=lc.end()&& *ilc < *ilb)
++ilc;
if(ilc==lc.end())
lc.push_back(*ilb);
else if(*ilc== *ilb)
*ilc+= *ilb;
else
lc.insert(ilc, *ilb);
}
lc.remove_if(EqualZero());
return lc;
}
List SubList(List &la,List &lb)
{
List lc(lb);
iList ilc;
for(ilc=lc.begin();ilc!=lc.end();++ilc)
{
ilc->first=-ilc->first;
}
return AddList(la,lc);
}
List MulList(List &la,List &lb)
{
List lc;
iList ilb,ilt;
for(ilb=lb.begin();ilb!=lb.end();++ilb)
{
List temp(la);
for(ilt=temp.begin();ilt!=temp.end();++ilt)
{
*ilt*= *ilb;
}
lc=AddList(lc,temp);
}
return lc;
}
int main()
{
List la,lb,lc;
InputList(la);
InputList(lb);
ShowList(la);
ShowList(lb);
lc=AddList(la,lb);
ShowList(lc);
lc=SubList(la,lb);
ShowList(lc);
lc=MulList(la,lb);
ShowList(lc);
system("PAUSE");
return 0;
}