⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 muzi.txt

📁 利用C语言实现两个多项式的加法
💻 TXT
字号:
/*实现多项式的加法*/
/*依次输入多项式的指数和系数,多项式的输入以(0,0)作为结束标志*/

#include <malloc.h>
#define NULL 0
#define LEN sizeof(struct lnode)

int n;
struct lnode
{
 int mc;
 int mn;
 struct lnode *next;
};

struct lnode *create()    /*建立多项式*/
{
 struct lnode *head;
 struct lnode *p1,*p2;
 n=0;
 p1=p2=(struct lnode *)malloc(LEN);
 scanf("%d  %d",&p1->mc,&p1->mn);
 head=NULL;
 while(p1->mc!=0 || p1->mn!=0)
 {
  n++;
  if(n==1)head=p1;
  else p2->next=p1;
  p2=p1;
  p1=(struct lnode *)malloc(LEN);
  scanf("%d  %d",&p1->mc,&p1->mn);
 }
 p2->next=NULL;
 return head;
}

void print(struct lnode *head)   /*输出多项式*/
{
 struct lnode *p;
 printf("\n\nthese values are\n\n");
 p=head;
 if(head !=NULL)
   do
   {
    printf("%d    ",p->mc);
    p=p->next;
    }while(p!=NULL);
 printf("\n\n");
 p=head;
 if(head !=NULL)
   do
   {
    printf("%d    ",p->mn);
    p=p->next;
    }while(p!=NULL);
  printf("\n\n");
}

struct lnode * Add(struct lnode *p1,struct lnode *p2)  /*多项式相加*/
{
 struct lnode *p,*q;
 p=q=(struct lnode *)malloc(LEN);
 p->mc=0;
 p->mn=0;
 while(p1 && p2)
 {
  if(p1->mc<p2->mc)
  {
   p->next=p1;p=p1;p1=p1->next;
   }
   else if(p1->mc>p2->mc)
   {
    p->next=p2;p=p2;p2=p2->next;
   }   
   else
   {
    p1->mn+=p2->mn;p->next=p1;p=p1;p1=p1->next;p2=p2->next;
    }
  }
  p->next=p1?p1:p2;
 return q->next;
}

main()
{
  struct lnode *P,*Q,*R;
  printf("input the first formula\n");
  P=create();
  print(P);
  n=0;
  printf("\n\ninput the second formula\n");
  Q=create();
  print(Q);
  R=Add(P,Q);
  print(R);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -