📄 duoxiangshi.c
字号:
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
#include <conio.h>
#define Null 0
#define True 1
#define False 0
typedef struct polyterm
{
int coef;
int exp;
struct polyterm *next;
}TERM;
TERM *reverse(TERM *q);
void polyout(TERM *head);
TERM *creatpoly() /**/
{
TERM *head,*r,*s;
int m,n;
head=(TERM *)malloc(sizeof(TERM));
printf("input coef and exp(1,2<CR>):\n");
scanf("%d,%d",&n,&m);
r=head;
while(n)
{
s=(TERM *)malloc(sizeof(TERM));
s->coef=n;
s->exp=m;
r->next=s;
r=s;
printf("\nInput coef and exp:\n");
scanf("%d,%d",&n,&m);
}
r->next=Null;
head=head->next;
return (head);
} /* creatpoly */
TERM *polyadd(TERM *ha,TERM *hb)
{
TERM *hc,*p,*q,*s,*r;
int x;
p=ha;
q=hb;
hc=(TERM *)malloc(sizeof(TERM));
s=hc;
while((p!=Null)&&(q!=Null))
{
if(p->exp==q->exp) /* coeficients */
{
x=p->coef+q->coef;
if(x!=0)
{
r=(TERM *)malloc(sizeof(TERM));
r->exp=p->exp;
r->coef=x;
s->next=r;
s=r;
}
p=p->next;
q=q->next;
}
else if(p->exp<q->exp)
{
r=(TERM *)malloc(sizeof(TERM));
r->coef=q->coef;
r->exp=q->exp;
s->next=r;
s=r;
q=q->next;
}
else /* p->exp>q->exp */
{
r=(TERM *)malloc(sizeof(TERM));
r->exp=p->exp;
r->coef=p->coef;
s->next=r;
s=r;
p=p->next;
}
}
while(p!=Null)
{
r=(TERM *)malloc(sizeof(TERM));
r->exp=p->exp;
r->coef=p->coef;
s->next=r;
s=r;
p=p->next;
}
while(q!=Null)
{
r=(TERM *)malloc(sizeof(TERM));
r->exp=q->exp;
r->coef=q->coef;
s->next=r;
s=r;
q=q->next;
}
s->next=Null;
r=hc;
hc=hc->next;
free(r);
return (hc);
} /*polyadd */
TERM *polymulti(TERM *f,TERM *g) /* */
{
TERM *fp,*gp,*hp,*q,*h;
int maxp,p,r,x;
maxp=f->exp+g->exp;
h=(TERM *)malloc(sizeof(TERM));
hp=h;
g=reverse(g);
for(r=maxp;r>=0;r--)
{
x=0;
fp=f;
gp=g;
while((fp!=Null)&&(gp!=Null))
{
p=fp->exp+gp->exp;
if(p>r)
fp=fp->next;
else if(p<r)
gp=gp->next;
else
{
x+=fp->coef*gp->coef;
fp=fp->next;
gp=gp->next;
}
} /*end of while */
if(x!=0)
{
q=(TERM *)malloc(sizeof(TERM));
q->exp=r;
q->coef=x;
q->next=Null;
hp->next=q;
hp=q;
}
}/* end of for */
hp=h;
h=h->next;
free(hp);
return (h);
}
TERM* reverse(TERM *q)
{
TERM *p1,*p2;
if(q!=Null)
{
p1=q->next;
q->next=Null;
while(p1!=Null)
{
p2=p1->next;
p1->next=q;
q=p1;
p1=p2;
} /* end of while */
}
return (q);
}
void polyout(TERM *head)
{
TERM *p;
p=head;
/* p=head->next; */
while(p!=Null)
{
printf("%d,%d ",p->coef,p->exp);
p=p->next;
}
printf("\n");
}
void main()
{
TERM *ha,*hb,*hc,*h;
printf("\nInput the 1st polynomial");
ha=creatpoly();
printf("\nInput the 2nd polynomial");
hb=creatpoly();
printf("\nthe 1st polynomial is:");
polyout(ha);
printf("\nthe 2nd polynomial is:");
polyout(hb);
hc=polyadd(ha,hb);
printf("\nthe addition of the two polynomial is:");
polyout(hc);
h=polymulti(ha,hb);
printf("\nthe multiplication of the two polynomial is:");
polyout(h);
getch();
return ;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -