主题:[原创]大侠帮我看下"多项式相加“为什么编译通过,输不出结果?
#include<iostream>
using namespace std;
class list{
public:
int coef,exp;
class list *next;
};
typedef class list node;
typedef node *link;
link creat_link(int data[4]);
void print_link(link head);
link sum_link(link a,link b);
int main(){
link a,b,c;
int data1[4]={3,0,4,2};
int data2[4]={6,8,6,9};
cout<<"原始多项式"<<"A="; //*****
a=creat_link(data1);
b=creat_link(data2);
print_link(a);
cout<<"B=";
print_link(b);
cout<<"多项式相加结果\nC=";
c=sum_link(a,b);
print_link(c);
return 0;
}
link creat_link(int data[4]){
link head,newnode,ptr;
for(int i=0;i<4;i++){
newnode = new node;
if(!newnode){
cout<<"Error!内存申请失败!"<<endl;
exit(1);
}
if(i=0){
newnode->coef=data[i];
newnode->exp=3-i;
newnode->next=NULL;
head=newnode;
ptr=head;
}
else if(data[i]!=0){
newnode->coef=data[i];
newnode->exp=3-i;
newnode->next=NULL;
ptr->next=newnode;
ptr=newnode;
}
}
return head;
}
void print_link(link head){
while(head!=NULL){
if(head->exp==1 && head->coef!=0)
cout<<head->coef<<"X + ";
else if(head->exp!=0 && head->coef!=0)
cout<<head->coef<<"X^"<<head->exp<<" + ";
else if(head->coef!=0)
cout<<head->next;
head=head->next;
}
cout<<endl;
}
link sum_link(link a,link b){
int sum[4],i=0;
link ptr;
ptr=b;
while(a!=NULL){
b=ptr; //重复比较A和B的指数
while(b!=NULL){
if(a->exp==b->exp){
sum[i]=a->coef+b->coef;
a=a->next;
b=b->next;
i++;
}
else if(b->exp > a->exp){
sum[i]=b->coef;
b=b->next;
i++;
}
else if(a->exp > b->exp){
sum[i]=a->exp;
a=a->next;
i++;
}
}
}
return creat_link(sum);
}
using namespace std;
class list{
public:
int coef,exp;
class list *next;
};
typedef class list node;
typedef node *link;
link creat_link(int data[4]);
void print_link(link head);
link sum_link(link a,link b);
int main(){
link a,b,c;
int data1[4]={3,0,4,2};
int data2[4]={6,8,6,9};
cout<<"原始多项式"<<"A="; //*****
a=creat_link(data1);
b=creat_link(data2);
print_link(a);
cout<<"B=";
print_link(b);
cout<<"多项式相加结果\nC=";
c=sum_link(a,b);
print_link(c);
return 0;
}
link creat_link(int data[4]){
link head,newnode,ptr;
for(int i=0;i<4;i++){
newnode = new node;
if(!newnode){
cout<<"Error!内存申请失败!"<<endl;
exit(1);
}
if(i=0){
newnode->coef=data[i];
newnode->exp=3-i;
newnode->next=NULL;
head=newnode;
ptr=head;
}
else if(data[i]!=0){
newnode->coef=data[i];
newnode->exp=3-i;
newnode->next=NULL;
ptr->next=newnode;
ptr=newnode;
}
}
return head;
}
void print_link(link head){
while(head!=NULL){
if(head->exp==1 && head->coef!=0)
cout<<head->coef<<"X + ";
else if(head->exp!=0 && head->coef!=0)
cout<<head->coef<<"X^"<<head->exp<<" + ";
else if(head->coef!=0)
cout<<head->next;
head=head->next;
}
cout<<endl;
}
link sum_link(link a,link b){
int sum[4],i=0;
link ptr;
ptr=b;
while(a!=NULL){
b=ptr; //重复比较A和B的指数
while(b!=NULL){
if(a->exp==b->exp){
sum[i]=a->coef+b->coef;
a=a->next;
b=b->next;
i++;
}
else if(b->exp > a->exp){
sum[i]=b->coef;
b=b->next;
i++;
}
else if(a->exp > b->exp){
sum[i]=a->exp;
a=a->next;
i++;
}
}
}
return creat_link(sum);
}