多项式合并: F(x)=8x7+7x4+3x2+x+2x-2+8x-3 G(x)=9x6+2x5+5x4-x+5

来源:互联网 发布:龙岗做网络推广公司 编辑:程序博客网 时间:2024/05/17 02:57

多项式合并:

F(x)=8x7+7x4+3x2+x+2x-2+8x-3

G(x)=9x6+2x5+5x4-x+5

======================================================

源代码:

#include <iostream>

using namespace std;

#include <list>

 

class Term

{

public:

Term(int c,int e):coef(c),exp(e){}

int getcoef();

int getexp();

private:

int coef;

int exp;

};

int Term::getcoef()

{

return coef;

}

int Term::getexp()

{

return exp;

}

 

int main()

{

void sort(list<Term> alist);

void merge(list<Term> alist,list<Term> blist);

list<Term> alist,blist;

int array1[]={8,7,3,1,2,8,9,2,5,-1,5};

int array2[]={7,4,2,1,-2,-3,6,5,4,1,0};

int i,j;

for(i=0;i<=5;i++)

{

Term t1(array1[i],array2[i]);

alist.push_back(t1);

}

cout<<"F(x)=";

sort(alist);

for(j=6;j<=10;j++)

{

Term t2(array1[j],array2[j]);

blist.push_back(t2);

}

cout<<"G(x)=";

sort(blist);

    merge(alist,blist);

return 0;

}

 

void merge(list<Term> alist,list<Term> blist)

{

void sort(list<Term> alist);

list<Term> clist;

list<Term>::iterator a,b,c;

a=alist.begin();

b=blist.begin();

c=clist.begin();

while(a!=alist.end() && b!=blist.end())

if((*a).getexp() == (*b).getexp()){ 

Term t3((*a).getcoef()+(*b).getcoef(),(*a).getexp());

clist.push_back(t3); 

a++; 

b++;

}else if((*a).getexp() > (*b).getexp()){

clist.push_back(*a);

a++;

}else{

clist.push_back(*b);

b++;

}

if(a==alist.end()){

while(b!=blist.end()){    

clist.push_back(*b);    

b++;    

}

}else if(b==blist.end()){

while(a!=alist.end()){ 

clist.push_back(*a); 

a++;

}

}

}

cout<<"合并多项式:"<<endl<<"M(x)=";

sort(clist);

}

void sort(list<Term> alist)

{

list<Term>::iterator a;

for(a=alist.begin();a!=alist.end();a++)

{

if((*a).getcoef()!=0){

if( ((a!=alist.begin()) && ((*a).getcoef()>0)) ){

if( (*a).getcoef()==1 ){

cout<<"+";

}else{

cout<<"+"<<(*a).getcoef();

}

}else{

if((*a).getcoef()!=1){

if((*a).getcoef()==-1){

cout<<"-";

}else{

cout<<(*a).getcoef();

}

}

}

if((*a).getexp() != 0){

if((*a).getexp()==1){

cout<<"x";

}else{

cout<<"x^"<<(*a).getexp();

}

}

}

}

cout<<endl;

}

 

 

 

 

 

0 0
原创粉丝点击