📄 二元组表多项式相加.cpp
字号:
#include<iostream>
using namespace std;
//**************************
const int maxterm = 100;
class polynomial;
//---------------------------------------
class term {
friend class polynomial;
private:
float coef;
int exp;
public:
term() { coef = 0; exp = 0; }
};
//-----------------------------------------------------------------
class polynomial {
static term termarray[maxterm];
static int free;
int start,finish;
public:
polynomial(){ start = free; finish = start-1; }
polynomial(const polynomial &p){ start = p.start; finish = p.finish; }
polynomial add(polynomial &B); //*
void set();
void newterm(float, int);
void print();
};
//--------------------------------------------
term polynomial::termarray[maxterm];
int polynomial::free = 0;
//--------------------------------------------
void polynomial::set() {
int n;
cout<<"输入项数:"<<endl;
cin>>n;
finish = start+n-1;
for(int i = 0; i < n; i++)
{
cout<<"输入第"<<i+1<<"项的系数和指数:"<<endl;
cin>>termarray[free].coef>>termarray[free].exp; free++;
}
}
//-------------------------------------------------------------------------
polynomial polynomial::add (polynomial &B) {
polynomial C;
int a = start;
int b = B.start;
C.start = free;
float c;
while(a<=finish && b<=B.finish)
{
if(termarray[a].exp==termarray[b].exp)
{
c = termarray[a].coef +termarray[b].coef ;
if(c!=0) newterm(c, termarray[a].exp);
a++;b++;
}
else
{
if(termarray[a].exp < termarray[b].exp)
{
newterm( termarray[a].coef,termarray[a].exp );
a++;
}
else
{
newterm(termarray[b].coef,termarray[b].exp );
b++;
}
}
}
//*
while(a<=finish) { newterm(termarray[a].coef,termarray[a].exp ); a++; }
while(b<=B.finish) { newterm(termarray[b].coef,termarray[b].exp ); b++ ;}
C.finish = free-1;
return C;
}
//*
void polynomial::newterm (float c,int e) {
if(free >= maxterm-1) { cout<<"too many terms in polynomials"<<endl; return ; }
termarray[free].coef = c;
termarray[free].exp = e;
free++;
}
void polynomial::print () {
int k = 0;
while(k < finish-start+1)
{
cout<<"第"<<k+1<<"项的系数和指数分别为:"<<endl;
cout<<termarray[start+k].coef<<" "<<termarray[start+k].exp<<endl; k++;
}
}
//********************************************************
void main() {
polynomial AA; AA.set ();
polynomial BB; BB.set ();
polynomial sum(AA.add (BB));
cout<<"相加结果为:"<<endl;
sum.print ();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -