程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C語言多項式相加程序

C語言多項式相加程序

編輯:關於C語言
 

多項式相加程序代碼(C語言) ,供那些c語言初學者參考。

 

#i nclude<stdio.h>
#i nclude<malloc.h>
#i nclude<stdlib.h>
#define  LEN  sizeof(node)


typedef struct polynode
{
 int coef;
 int exp;
 struct polynode *next;
}node;


node * create(void)
{
 node *h,*r,*s;
 int c,e;
 h=(node *)malloc(LEN);
 r=h;
 printf("coef:");
 scanf("%d",&c);
 printf("exp: ");
 scanf("%d",&e);
 while(c!=0)
 {
  s=(node *)malloc(LEN);
  s->coef=c;
  s->exp=e;
     r->next=s;
     r=s;
     printf("coef:");
     scanf("%d",&c);
     printf("exp: ");
     scanf("%d",&e);

 }
 r->next=NULL;
 return(h);
}

 

polyadd(node *polya, node *polyb)
{
 node *p,*q,*pre,*temp;
 int sum;
 p=polya->next;
 q=polyb->next;
 pre=polya;
 while(p!=NULL&&q!=NULL)
 {
  if(p->exp<q->exp)
  {
   pre->next=p;pre=pre->next;
   p=p->next;
  }
  else if(p->exp==q->exp)
  {
   sum=p->coef+q->coef;
   if(sum!=0)
   {
    p->coef=sum;
    pre->next=p;pre=pre->next;
    p=p->next;temp=q;q=q->next;free(temp);
   }
   else
   {temp=p->next;free(p);p=temp;
    temp=q->next;free(q);q=temp;
   }
     }
 else
 {pre->next=q;pre=pre->next;
  q=q->next;
 }
    }
if(p!=NULL)
pre->next=p;
else
pre->next=q;                                                        
}


void print(node * p)
{                                                                                                     
    while(p->next!=NULL)
    {  
        p=p->next;
        printf("     %d*x^%d",p->coef,p->exp);  
          
    }
}  

main()
{
 node * polya,* polyb;
 printf("Welcome to use!\n");
 printf("\nPlease input the ploya include coef && exp:\n");
 polya=create();
 print(polya);
 printf("\nPlease input the ployb include coef && exp:\n");
 polyb=create();
 print(polyb);
    printf("\nSum of the poly is:\n");
    polyadd(polya,polyb);
    print(polya);
    printf("\n");
}

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved