1 Star 0 Fork 0

hsmath/PAT advanced

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
1002.cpp 2.39 KB
一键复制 编辑 原始数据 按行查看 历史
Shuang Hu 提交于 2021-03-22 19:29 . My patest code
#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;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/hsmath/pat-advanced.git
git@gitee.com:hsmath/pat-advanced.git
hsmath
pat-advanced
PAT advanced
master

搜索帮助