本文共 2633 字,大约阅读时间需要 8 分钟。
/**############################################################################1、 结果多项式另存2、 扫描两个相加多项式,若都未检测完: 2.1、若当前被检测项指数相等,系数相加。 若未变成 0,则将结果加到结果多项式。 2.2、若当前被检测项指数不等, 将指数小者加到结果多项式。3、 若有一个多项式已检测完, 将另一个多项式剩余部分复制到结果多项式。############################################################################*/#include <iostream>using namespace std;#define maxTerms 100 //存放指系数的长度class term{ public: //系数 float coef; //指数 int exp;};class Polynomial{ private: //当前空闲位置指针 static int free; //多项式始末位置 int start,finish; //项数组 static term termArray[maxTerms];public: Polynomial operator+(Polynomial B); void NewTerm(float c, int e); char compare(int a, int b); void Print(); void create();};term Polynomial::termArray[maxTerms];int Polynomial::free;void Polynomial::Print(){ int n = start; for(int i = n; i<= finish; i++){ cout<<"系数="<<termArray[i].coef<<" "; } cout<<endl; n = start; for(i = n; i<= finish; i++){ cout<<"指数="<<termArray[i].exp<<" "; } cout<<endl;}void Polynomial::create(){ cout<<"###############################################"<<endl; start = finish = free = (free>0)?free:0; char ch = 'a'; while(ch!='#'){ cout<<"系数:"; cin>>termArray[free].coef; cout<<"指数:"; cin>>termArray[free].exp; free++; cout<<"是否继续添加[输入#结束]:"<<endl; cin>>ch; } finish = free - 1;}char Polynomial::compare(int a, int b){ if( a==b ){ return '='; }else if( a>b ) { return '>'; }else if( a<b ) { return '<'; } return '\n';}//把一个新的项加到多项式C(x)中void Polynomial::NewTerm(float c, int e){ if( free>=maxTerms ){ cout<<"Too many terms in polynomials"<<endl; exit(1); } termArray[free].coef = c; //系数 termArray[free].exp = e; //指数 free++;}Polynomial Polynomial::operator+(Polynomial B){ Polynomial C; int a = start; int b = B.start; C.start = free; float c; while( a<=finish && b<=B.finish ){ //比较对应项指数 switch( compare(termArray[a].exp, termArray[b].exp) ) { case '='://指数相等 //系数相加 c = termArray[a].coef + termArray[b].coef; if(c) NewTerm(c, termArray[a].exp); a++; b++; break; case '>': //b指数小, 建立新项 NewTerm(termArray[b].coef, termArray[b].exp); b++; break; case '<': NewTerm(termArray[a].coef, termArray[a].exp); a++; break; } } //a未检测完时 for(; a<=finish; a++) NewTerm(termArray[a].coef, termArray[a].exp); //b未检测完时 for(; b<=B.finish; b++) NewTerm(termArray[b].coef, termArray[b].exp); C.finish = free - 1; return C;}int main(){ Polynomial A; A.create(); A.Print(); Polynomial B; B.create(); B.Print(); Polynomial C = A + B ; cout<<endl; cout<<endl; cout<<endl; A.Print(); cout<<"+++++++++++++++++++++++++++++++++++++++++++++++++++++"<<endl; B.Print(); cout<<"====================================================="<<endl; C.Print(); return 0;} 转载地址:http://dgmna.baihongyu.com/