C++实现两个多项式相加

C++实现两个多项式相加,具体代码如下:

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct PNode)
 struct PNode
 {float coef;
 int expn;
 struct PNode *next;
 };
 
void print(PNode* p)
{
PNode *r;  int i;
if(!p)
printf("this is a kongbiao");
r=p->next;
printf("p(x)=");
while(p&&(r->next))
{
 printf("%d",r->coef);
 for(i=1;i<r->expn;i++)
   printf("x*");
 printf("x");
 printf("+");
 r=r->next;
}
printf("%d",r->coef);
 for(i=1;i<r->expn;i++)
   printf("x*");
 printf("x");
}
 
 
 
 struct PNode* CreatPolyn(struct PNode *P1,int m)
{
int i;
struct PNode *s,*p;
 
s=(struct PNode*)malloc(LEN);
if(!s)
 {
  printf("内存分配失败,程序结束!");
  exit(1);
 }
s->next=NULL;
P1=s;
for(i=1;i<=m;i++)
{
   p=(struct PNode*)malloc(LEN);
   printf("请按指数的升幂输入一元多项式的系数和指数:\n");
   scanf("%d,%d",&p->coef,&p->expn);
   printf("\n");
s->next=p;
s=p;
}
s->next=NULL;
return P1;
}
 
 
 
struct PNode* AddPolyn(struct PNode *Pa,struct PNode *Pb)
{PNode *ha,*hb,*qa,*qb;  float sum;  PNode *s;
 ha=Pa;hb=Pb;
   if(ha->next!=0)qa=ha->next;if(hb->next!=0)qb=hb->next;  
   while(qa&&qb)
   {
if(qa->expn==qb->expn)
{ sum=qa->coef+qb->coef;
        if(sum!=0.0)
  {    qa->coef=qa->coef+qb->coef;  }
  else{ 
 free(qb);free(qa);
}}
if(qa->expn>qb->expn) //pb项插在pa项前面
{
   s=(PNode*)malloc(LEN);
      s->coef=qb->coef;
   s->next=qa;  ha->next=s;
       ha=ha->next;
    free(qb);}
             
if(qa->expn<qb->expn)//pb插在pa的后面
{
   s=(PNode*)malloc(LEN);
      s->coef=qb->coef;
   s->next=qa->next;
   qa->next=s;
    free(qb);
       
   }
 
   }
return Pa;}
 
 
void main()
{int i,m;
  struct PNode *Pa,*Pb,*pc;
  printf("请输入一元多项式pa的项数:\n");
   scanf("%d",&m);
   Pb=CreatPolyn(Pb,i);
printf("请输入一元多项式pb的项数:\n");
   scanf("%d",&i);
Pa=CreatPolyn( Pa,m);  转载请注明圣安娜娱乐http://www.leruntoys.com

posted on 2013-07-29 16:19  琴深  阅读(1630)  评论(0编辑  收藏  举报

导航