具备一元多项式加、减、乘的运算功能.(多项式系数的输入和输出均按次数从高到低排列形式安排系数.,最右面的为零次项系数,从右向左依次增加.)例如:多项式加法 输入:2 -5 0 7 (表示多
来源:学生作业帮助网 编辑:六六作业网 时间:2024/11/13 03:42:29
具备一元多项式加、减、乘的运算功能.(多项式系数的输入和输出均按次数从高到低排列形式安排系数.,最右面的为零次项系数,从右向左依次增加.)例如:多项式加法 输入:2 -5 0 7 (表示多
具备一元多项式加、减、乘的运算功能
.(多项式系数的输入和输出均按次数从高到低排列形式安排系数.,最右面的为零次项系数,从右向左依次增加.)
例如:多项式加法
输入:2 -5 0 7 (表示多项式 2x3-5x2+7)
3 1 -8 (表示多项式 3x2+x-8)
输出 2 -2 1 -1
(2x3-5x2+7)+( 3x2+x-8)= 2x3-2x2+x-1
输入的数据项数是不定长的,最多不超过10项,用菜单让用户选择运算类别.
菜单格式如下:
具备一元多项式加、减、乘的运算功能.(多项式系数的输入和输出均按次数从高到低排列形式安排系数.,最右面的为零次项系数,从右向左依次增加.)例如:多项式加法 输入:2 -5 0 7 (表示多
这个程序是我们课设题目,只实现了一元多项式的相加,然后对(addpoly )实现相加的函数修改一下,很简单就能达到相减的目的.
代码如下:
#include "stdio.h"
#include "malloc.h"
typedef struct polynode
{
int coef;
int expn;
struct polynode *next;
} *pnode;
pnode createpoly()
{
int a,n,i=1;
pnode head,s,p;
printf("输入一元多项式(以0,0标志结束):\n");
printf("要求:1.按幂从大到小次序输入各节点\n");
printf(" 2.没有两个节点具有相同的幂:\n");
head=(pnode) malloc (sizeof (struct polynode ));
head->next=NULL;
p=head;
do
{
printf("第%d次->系数,幂:",i++);
scanf("%d,%d",&a,&n);
if (a!=0 || n!=0)
{
s=(pnode) malloc ( sizeof (struct polynode));
s->coef=a; s->expn=n; s->next=NULL;
p->next=s; p=s;
}
}
while (a!=0 || n!=0);
printf("\n");
return (head);
}
void printpoly(pnode head)
{
int first=1;
head=head->next;
while (head!=NULL)
{
if (first)
{
if (head->expn==1)
printf("%dx",head->coef);
else if (head->expn==0)
printf("%d",head->coef);
else
printf("%dx^%d",head->coef,head->expn);
first=0;
}
else
{
if (head->expn==1)
printf("%+dx",head->coef);
else if (head->expn==0)
printf("%+d",head->coef);
else
printf("%+dx^%d",head->coef,head->expn);
}
head=head->next;
}
printf("\n");
}
pnode addpoly(pnode pa,pnode pb)
{
int n;
pnode pc,s,p;
pa=pa->next;
pb=pb->next;
pc=(pnode) malloc (sizeof (struct polynode));
pc->next=NULL;p=pc;
while (pa!=NULL && pb!=NULL)
{
if (pa->expn>pb->expn)
{
s= (pnode) malloc (sizeof (struct polynode));
s->coef=pa->coef; s->expn=pa->expn;
s->next=NULL; p->next=s; p=s;
pa=pa->next;
}
else if (pa->expnexpn)
{
s=(pnode) malloc (sizeof (struct polynode));
s->coef=pb->coef; s->expn=pb->expn;
s->next=NULL; p->next=s; p=s;
pb=pb->next;
}
else
{
n=pa->coef+pb->coef;
if (n!=0)
{
s=(pnode) malloc (sizeof (struct polynode));
s->coef=n; s->expn=pb->expn; s->next=NULL;
p->next=s; p=s;
}
pa=pa->next; pb=pb->next;
}
}
while (pa!=NULL)
{
s=(pnode) malloc (sizeof (struct polynode));
s->coef=pa->coef; s->expn=pa->expn;
s->next=NULL; p->next=s;
p=s; pa=pa->next;
}
while (pb!=NULL)
{
s= (pnode) malloc (sizeof (struct polynode ));
s->coef=pb->coef; s->expn=pb->expn;
s->next=NULL; p->next=s;
p=s; pb=pb->next;
}
return(pc);
}
main()
{
pnode poly1,poly2,poly3;
printf("建立第一个一元多项式=>\n");
poly1=createpoly();
printf("建立第二个一元多项式=>\n");
poly2=createpoly();
poly3=addpoly(poly1,poly2);
printf("第一个一元多项式为:");
printpoly (poly1);
printf("第二个一元多项式为:");
printpoly(poly2);
printf("相加后一元多项式为:");
printpoly(poly3);
}