代码拉取完成,页面将自动刷新
#include <iostream>
#include <iomanip>
using namespace std;
class Polynomial{
private:
class monomial{
public:
int exponent;
double coefficient;
monomial* next;
monomial(int e,double c){
exponent=e;
coefficient=c;
next=NULL;
}
};
monomial* first;//mark the first one
public:
Polynomial(){
first=NULL;
}
void BuildAPolynomial(int num);
monomial* getFirst(){
return first;
}
void insert(int exp,double coe);
// ~Polynomial(){
// monomial* p1=first;
// while(p1->next){
// monomial* p2=p1;
// p1=p1->next;
// delete p2;
// }
// delete p1;
// }
void PrintPolynomial(){
monomial* p1=first;
int num=0;
while(p1){
p1=p1->next;
num++;
}
p1=first;
cout<<num;
if(p1){
cout<<" ";
}
while(p1){
if(p1->next){
cout<<p1->exponent<<" "<<setiosflags(ios::fixed)<<setprecision(1)<<p1->coefficient<<" ";
}
else{
cout<<p1->exponent<<" "<<setiosflags(ios::fixed)<<setprecision(1)<<p1->coefficient;
}
p1=p1->next;
}
cout<<endl;
}
void AddPolynomial(Polynomial P1,Polynomial P2);
};
void Polynomial::BuildAPolynomial(int num){
double coe;
int exp;
for(int i=0;i<num;i++){
cin>>exp>>coe;
insert(exp,coe);
}
}
void Polynomial::insert(int exp,double coe){
monomial* M1=new monomial(exp,coe);
monomial* M2=first;
if(first==NULL){
first=M1;
}else{
while(M2->next){
M2=M2->next;
}
M2->next=M1;
}
}
int main(){
Polynomial P1;
Polynomial P2;
Polynomial P3;
int num1,num2;
cin>>num1;
P1.BuildAPolynomial(num1);
cin>>num2;
P2.BuildAPolynomial(num2);
P3.AddPolynomial(P1,P2);
P3.PrintPolynomial();
}
void Polynomial::AddPolynomial(Polynomial P1,Polynomial P2){
monomial* pt1=P1.getFirst();
monomial* pt2=P2.getFirst();
while(pt1&&pt2){
if(pt1->exponent>pt2->exponent){
insert(pt1->exponent,pt1->coefficient);
pt1=pt1->next;
}
else if(pt1->exponent<pt2->exponent){
insert(pt2->exponent,pt2->coefficient);
pt2=pt2->next;
}
else{
if(pt1->coefficient+pt2->coefficient){
insert(pt1->exponent,pt1->coefficient+pt2->coefficient);
}
pt1=pt1->next;
pt2=pt2->next;
}
}
while(pt1){
insert(pt1->exponent,pt1->coefficient);
pt1=pt1->next;
}
while(pt2){
insert(pt2->exponent,pt2->coefficient);
pt2=pt2->next;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。