多项式加法(C语言实现)

合集下载

C语言实现多项式的相加

C语言实现多项式的相加

C语⾔实现多项式的相加本⽂实例为⼤家分享了C语⾔多项式相加的具体代码,供⼤家参考,具体内容如下包含带头节点的链表的初始化,输出:#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>typedef struct Pol{int coe; // 系数int index; // 指数struct Pol *next;}Pol;int main(int argc, char *argv[]){Pol *head1 = NULL; // 第⼀个多项式Pol *head2 = NULL; // 第⼆个多项式Pol *Initiate(Pol *head1); // 声明初始化函数void Output(Pol *head); // 声明输出函数void PolAdd(Pol *head1, Pol *head2); // 声明相加函数int coe, index;char sign;Pol *p;int n = 0;// 初始化第⼀个多项式head1 = Initiate(head1);p = head1;while (1){scanf("%dx%d%c", &coe, &index, &sign);p->next = (Pol *)malloc(sizeof(Pol));p = p->next;p->coe = coe;p->index = index;p->next = NULL;if(sign == '\n')break;}printf("第⼀多项式输⼊完毕。

\n");// 初始化第⼆个多项式head2 = Initiate(head2);p = head2;while (1){scanf("%dx%d%c", &coe, &index, &sign);p->next = (Pol *)malloc(sizeof(Pol));p = p->next;p->coe = coe;p->index = index;p->next = NULL;if (sign == '\n')break;}printf("第⼆多项式输⼊完毕。

C语言多项式加法

C语言多项式加法

C语言题目-多项式加法多项式加法(10分)题目内容:一个多项式可以表达为x的各次幂与系数乘积的和,比如:2x6+3x5+12x3+6x+20现在,你的程序要读入两个多项式,然后输出这两个多项式的和,也就是把对应的幂上的系数相加然后输出。

程序要处理的幂最大为100。

输入格式:总共要输入两个多项式,每个多项式的输入格式如下:每行输入两个数字,第一个表示幂次,第二个表示该幂次的系数,所有的系数都是整数。

第一行一定是最高幂,最后一行一定是0次幂。

注意第一行和最后一行之间不一定按照幂次降低顺序排列;如果某个幂次的系数为0,就不出现在输入数据中了;0次幂的系数为0时还是会出现在输入数据中。

输出格式:从最高幂开始依次降到0幂,如:2x6+3x5+12x3-6x+20注意其中的x是小写字母x,而且所有的符号之间都没有空格,如果某个幂的系数为0则不需要有那项。

输入样例:6 25 33 121 60 206 25 32 121 60 20输出样例:4x6+6x5+12x3+12x2+12x+40时间限制:500ms内存限制:32000kb代码#include <stdio.h> //此程序需要分3种情况,一、幂为0;二、幂为1;三、幂大于1int a[105],b[105];int main(){intx,y;while (~scanf("%d%d",&x,&y)){//存储第一个多项式的数据,当幂为0时停止输入a[x]=y;if (x==0) break;}while (~scanf("%d%d",&x,&y)){//存储第二个多项式的数据,当幂为0时停止输入b[x]=y;if (x==0) break;}for (int i=0;i<=100;i++)a[i]=a[i]+b[i]; //将两个多项式的系数相加保存到数组a[i]中int flag=0; //用此数来区分输出的式子是否是第一个数字,是第一个式子flag就为0,不是第一个式子flag就为1for (int i=20;i>1;i--){if (a[i]){ //系数不为0if (a[i]>0){ //系数大于0的情况if (a[i]==1){ //系数等于1的情况if (flag==0){//输出的式子是第一个式子printf("x%d",i);flag=1;}else printf("+x%d",i); //输出的式子不是第一个式子}else{ //系数大于1的情况if (flag==0){printf("%dx%d",a[i],i);flag=1;}elseprintf("+%dx%d",a[i],i);}}else{ //系数小于0的情况if (a[i]==-1)printf("-x%d",i);elseprintf("%dx%d",a[i],i);}}}if (a[1]){if (a[1]>0){if (a[1]==1){if (flag==0){printf("x");flag=1;} elseprintf("+x");}else{if (flag==0){printf("%dx",a[1]); flag=1;} elseprintf("+%dx",a[1]);}}else{if (a[1]==-1)printf("-x");elseprintf("%dx",a[1]);}}if (a[0]>0){if (flag==0){printf("%d",a[0]);flag=1;}elseprintf("+%d",a[0]);}if (a[0]<=0){printf("%d",a[0]);}printf("\n");return 0;}【下载本文档,可以自由复制内容或自由编辑修改内容,更多精彩文章,期待你的好评和关注,我将一如既往为您服务】。

多项式相加c语言

多项式相加c语言
Print(&sum);
reset(&p);
reset(&q);
reset(&sum);
return 0;
}
```
在上述代码中,首先定义了一个`Node`结构体,包含多项式的系数和指数,并通过链表的方式存储多项式的每一项。然后,实现了一系列函数,包括多项式的增加、输出、相加和消除。在`main`函数中,调用这些函数来完成多项式的输入、相加和输出。
请注意,这只是一个简单的示例,实际应用中可能需要考虑更多的边界情况和错误处理。
以下是一个简单的 C 语言示例,展示了如何实现多项式相加:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义结构的数据部分
struct poly {it zhishu;float xishu;
};
// 定义一个多项式结构
typedef struct node {
s->date.xishu = s->date.xishu + s->next->date.xishu;
s->next = s->next->next;
} else {
s = s->next;
}
}
d = d->next;
}
}
// 链表的消除函数
void reset(Node *pList) {
Node *p = pList;
while (p->next) {
if (flog == 1)
printf(" + ");
else {

(C语言)加法运算实验报告

(C语言)加法运算实验报告

cout<<"两个多项式之和为:"<<endl;
cout<<"A+B=";
result(add(A,B));
cout<<endl;
return 0;
}
//当 p 不为空时进行循环;
{
PolyLink A,B;
A=Ini_polynode();
B=Ini_polynode();
cout<<"输入第一个多项式:"<<endl;
input(A);
cout<<"A=";
result(A);
cout<<"输入第二个多项式:"<<endl;
input(B);
cout<<"B=";
result(B);
2、 测试结果:
①输入 A=x+3x^6-8x^11
输入 B=6-3x^6+21x^9
输出 A+B=6+x+21x^9-8x^11
②输入 A=x+x^3
输入 B=-x-x^3
输出 A+B=0
③输入 A=x+x^100
输入 B=x^100+x^200
输出 A+B=x+2x^100+x^200
④输入 A=x+x^2+x^3
一元多项式的加法运算
一、 需求分析
1、 程序的基本功能 1 按照指数升序次序,输入并建立多项式 A 与 B。 2 计算多项式 A 与 B 的和,即建立多项式 A+B。 3 按照指数升序次序,输出多项式 A、B、A+B。 2、 输入输出要求: 1 输入多项式;

多项式相加c语言程序

多项式相加c语言程序

#include "stdafx.h"//备注:我用的编译平台所提供的头文件不是“stdio.h"#include"malloc.h"#include<cstdlib> //此头文件用来解决执行可以执行文件exe后直接退出的问题,希望可以帮到大家了解一个新函数和头文件typedef struct List{ //定义一个动态链表float coef;int expn;struct List *next;}*list;list initlist()//初始化,生成新结点{list l;l=(list)malloc(sizeof(List));if (!l) printf("error");l->next=NULL;return l;}void insertlist (list l,float *coe,int *exp)//每次scanf后插入结点,从链尾插入,main函数中定义一个链表尾指针{list s;s=(list)malloc(sizeof(List));if(!s)printf("error");s->coef=*coe;s->expn=*exp;l->next =s;s->next =NULL;}void putout(list l)//输出链表{list p;p=l->next;while(p->next){ if(p->expn==0)printf("1+");else if(p->coef==1&&p->expn==1){printf("x+");}elseprintf("%.2fx^%d+",p->coef,p->expn);p=p->next ;} if(p->expn==0)printf("1\n");else if(p->coef==1&&p->expn==1){printf("x\n");}elseprintf("%.2fx^%d\n",p->coef,p->expn);}int cmp(int f,int g) //比较函数,用来判定当前两多项式指数问题{if (f<g)return (-1);else if(f==g)return 0;elsereturn (1);}void addlist(list n,list m){//多项式相加list hn,hm,pn,pm;float sum;pn=n->next ;pm=m->next ;hn=n;hm=m;//定义一个当前节点的指针和一个头指针while(hn->next&&hm->next){switch (cmp(pn->expn,pm->expn))//比较两指数{case -1:hn=pn;pn=pn->next;break;case 0:sum=pn->coef +pm->coef ;if(sum!=0){pn->coef =sum;pm=pm->next ;free(hm->next);hm->next =pm;hn=hn->next ;pn=pn->next ;}//ifelse {hn->next =pn->next ;free(pn);pn=hn->next ;hm->next =pm->next ;free(pm);pm=hm->next ;}break;//elsecase 1:hm->next =pm->next ;hn->next=pm;pm->next =pn;hn=pm;pn=pn->next ;pm=hm->next ;break;}//switch}//whileif(hm->next ) //参考书本43页算法的思想,将剩余结点插入当前链表中{hn->next=pm;free(hm);}}//addlistvoid chongpaixu(list l)//将输入的多项式按升序排列,并将指数相同的合并(还不能执行){ list s;list q;list k;list w;float sum;k=initlist();q=l->next ;s=l;while(q->next){for(w=l ;q->next !=NULL;q=q->next ){for (s=s->next ;s->next!=NULL;s=s->next ){switch(cmp(s->expn,q->expn)){case -1:w=w->next ;break;case 1:k->coef=q->coef;q->coef=s->coef;s->coef=k->coef;k->expn=q->expn ;q->expn =s->expn ;s->expn =k->expn ;free(k);w=w->next ;break;case 0:sum=s->coef+q->coef;if(sum){s->coef=sum;s->next=q;free(q);q=s->next ;}//ifelse {w->next=q->next;free(s);free(q);s=w->next ;q=s->next ;}//elsebreak;}//switch}}}//while}void putmessage(void)//用来表明备注{printf("备注:该算法经过上课时老师给我们提出的问题进行了修改,不过关于排序的算法还不能完善\n");printf("因此,请输入时请将多项式按照升序输入,将相同指数合并!\n");printf("\n");printf("\n");printf("\n");printf("\n");printf("\n");printf("\n");}void main(){list l,s,hl,hs; int i,d,exp;float *q;int *w;float coe;putmessage();q=&coe;w=&exp;l=initlist();s=initlist();hl=l;hs=s;printf("请输入l的项数\n");scanf("%d",&d);if(d>0){for (i=0;i<d;i++){printf("请输入第%d项的系数\n",i+1);scanf("%f",&coe);printf("请输入第%d项的指数\n",i+1);scanf("%d",&exp);if(coe){insertlist(hl,q,w);hl=hl->next ;}}/*chongpaixu(l);*/if(l->next ){printf("你输入的多项式是f(x)=");putout(l);}else printf("你输入的多项式是f(x)=0\n"); }else printf("你输入的多项式l不存在\n");printf("请输入s的项数\n");scanf("%d",&d);if(d>0){for (i=0;i<d;i++){printf("请输入第%d项的系数\n",i+1);scanf("%f",&coe);printf("请输入第%d项的r指数\n",i+1);scanf("%d",&exp);if(coe){insertlist(hs,q,w);hs=hs->next ;}}if(s->next){printf("你输入的多项式是f(x)=");putout(s);}else printf("你输入的多项式是f(x)=0\n");}else printf("你输入的多项式不存在\n");hl=l;hs=s;if(hl->next &&hs->next ){addlist(l,s);printf("合并后的多项式f(x)=");if(l->next){putout(l);}else printf("0\n");}else printf("no add\n");system ( "pause" );//不加此语句,exe文件在执行完毕直接跳出}。

C语言实现多项式相加算法

C语言实现多项式相加算法
if(q->n==0&&q->xi<0)
printf("%0.2f",q->xi);
if(q->n==1&&q->xi==1)
printf("x");
if(q->n==1&&q->xi!=1&&q->xi>0)
printf("%0.2fx",q->xi);
if(p->n!=0&&p->n!=1&&p->xi==1)
printf("+x^%d",p->n); p=p->nexFra bibliotek; }
printf("\n");
}
main()
{
int i,j;
term *head1,*head2,*head3;
printf("请输入第一个多项式的项数:\n");
}
}
while(p!=NULL)
{
s=(term *)malloc(sizeof(term));
s->n=p->n;
s->xi=p->xi;
r->next=s;
r=s;
p=p->next;
}
while(q!=NULL)
q=head->next;
if(q->xi==0)
printf(" ");
if(q->n==0&&q->xi>0&&q->xi!=1)

多项式的运算(c语言实现)

多项式的运算(c语言实现)

#include"stdio.h"#include"stdlib.h"#include"conio.h"typedef struct Item{double coef;//系数int expn;//指数struct Item *next;}Item,*Polyn;#define CreateItem(p) p=(Item *)malloc(sizeof(Item));#define DeleteItem(p) free((void *)p);/************************************************************/ /* 判断选择函数 *//************************************************************/ int Select(char *str){ char ch;printf("%s\n",str);printf("Input Y or N:");do{ ch=getch();}while(ch!='Y'&&ch!='y'&&ch!='N'&&ch!='n');printf("\n");if(ch=='Y'||ch=='y') return(1);else return(0);}/************************************************************/ /* 插入位置定位函数 *//**************************************************************/ int InsertLocate(Polyn h,int expn,Item **p){ Item *pre,*q;pre=h;q=h->next;while(q&&q->expn<expn){ pre=q;q=q->next;}if(!q){ *p=pre;return(1);}else if(q->expn==expn){ *p=q;return(0);}else{ *p=pre;return(-1);}}/************************************************************/ /* 插入结点函数 *//************************************************************/ void insert(Item *pre,Item *p){p->next=pre->next;pre->next=p;}/************************************************************/ /* 输入多项式 */ /************************************************************/ Polyn Input(void){double coef;int expn,flag;Item *h,*p,*q,*pp;CreateItem(h);//产生头结点h->next=NULL;printf("input coef and expn(if end ,expn=-1)\n");while(1){scanf("%lf%d",&coef,&expn); //输入多项式的系数和指数if(expn==-1) break; //若指数为-,表示输入结束if(InsertLocate(h,expn,&pp))//返回值非表示插入新结点{ CreateItem(p);p->coef=coef;p->expn=expn;insert(pp,p);}else if(Select("has the same expn,Replace older value?")) pp->coef=coef; //指数相同,替换系数}return h;}/************************************************************/ /* 撤消多项式 */ /************************************************************/ void Destroy(Polyn h){Item *p=h,*q;while(p!=NULL){q=p;p=p->next;DeleteItem(q);}}/************************************************************/ /* 输出多项式 */ /************************************************************/ void Output(Polyn h,char *title){int flag=1;Item *p=h->next;printf("%s=",title);while(p){ if(flag) //表示是否是多项式的第一项{ flag=0;if(p->expn==0) printf("%.2lf",p->coef);else printf("%.2lfx^%d",p->coef,p->expn);}else{ if(p->coef>0) printf("+");if(p->expn==0) printf("%.2lf",p->coef);else printf("%.2lfx^%d",p->coef,p->expn);}p=p->next;}printf("\n");}/************************************************************//* 判断两个多项式项的关系 *//************************************************************/int ItemComp(Item x,Item y){ if(x.expn<y.expn)return(-1);else if(x.expn==y.expn)return(0);else return(1);}/************************************************************//* 两多项式多项式相加 *//************************************************************/Polyn AddPolyn(Polyn h1,Polyn h2){Item *head,*last,*pa=h1->next,*pb=h2->next,*s;CreateItem(head);head->next=NULL;last=head;while(pa&&pb){CreateItem(s);last->next=s;last=s;switch (ItemComp(*pa,*pb)){case -1:last->coef=pa->coef;last->expn=pa->expn;pa=pa->next;break;case 0:last->coef=pa->coef+pb->coef;last->expn=pa->expn;pa=pa->next;pb=pb->next;break;case 1:last->coef=pb->coef;last->expn=pb->expn;pb=pb->next;break;}}if(pa){while(pa){/*把剩余节点插入*/CreateItem(s);last->next=s;last=s;last->coef=pa->coef;last->expn=pa->expn;pa=pa->next;}} if(pb){while(pb){/*把剩余节点插入*/CreateItem(s);last->next=s;last=s;last->coef=pb->coef;last->expn=pb->expn;pb=pb->next;}} last->next=NULL;return head;}/************************************************************//* 两多项式多项式相减 *//************************************************************/Polyn SubtractPolyn(Polyn h1,Polyn h2){ Item *head,*last,*pa=h1->next,*pb=h2->next,*s;CreateItem(head);head->next=NULL;last=head;while(pa&&pb){CreateItem(s);last->next=s;last=s;switch (ItemComp(*pa,*pb)){case -1:last->coef=pa->coef;last->expn=pa->expn;pa=pa->next;break;case 0:last->coef=pa->coef-pb->coef;last->expn=pa->expn;pa=pa->next;pb=pb->next;break;case 1:last->coef=-(pb->coef);last->expn=pb->expn;pb=pb->next;break;}}if(pa){while(pa){/*把剩余节点插入*/CreateItem(s);last->next=s;last=s;last->coef=pa->coef;last->expn=pa->expn;pa=pa->next;}} if(pb){while(pb){/*把剩余节点插入*/CreateItem(s);last->next=s;last=s;last->coef=-(pb->coef);last->expn=pb->expn;pb=pb->next;}}last->next=NULL;return head;}/************************************************************//* 两多项式多项式相乘 *//************************************************************/Polyn MultPolyn(Polyn h1,Polyn h2) //两个多项式相乘{ int item,expn;Item *head,*pa,*pb=h2->next,*s,*pp;double coef;CreateItem(head);head->next=NULL;while(pb){pa=h1->next;while(pa){expn=pa->expn+pb->expn;coef=pa->coef*pb->coef;if(InsertLocate(head,expn,&pp)){CreateItem(s);s->coef=coef;s->expn=expn;insert(pp,s);}elsepp->coef=pp->coef+pa->coef;pa=pa->next;}pb=pb->next;}return head;}/************************************************************//* 菜单选择 *//************************************************************/int menu(void){ int num;system("cls");printf("%20c1--create P(x)\n",' ');printf("%20c2--create Q(x)\n",' ');printf("%20c3--p(x)+Q(x)\n",' ');printf("%20c4--P(x)-Q(x)\n",' ');printf("%20c5--p(x)*Q(x)\n",' ');printf("%20c6--print P(x)\n",' ');printf("%20c7--print Q(x)\n",' ');printf("%20c8--print P(x)+Q(x)\n",' ');printf("%20c9--print P(x)-Q(x)\n",' ');printf("%20c10--print P(x)*Q(x)\n",' ');printf("%20c11--Quit\n",' ');printf(" please select 1,2,3,4,5,6,7,8,9,10,11:");do{scanf("%d",&num);}while(num<1 || num>11);return(num);}/************************************************************//* 判断多项式是否存在 *//************************************************************/int PolynNotEmpty(Polyn h,char *p){ if(h==NULL){ printf("%s is not exist!\n",p);getchar();return(0);}else return(1);}/************************************************************//* 主函数 *//************************************************************/ void main(){ int num;Polyn h1=NULL; //指向p(x) 指针Polyn h2=NULL; //指向Q(x) 指针Polyn h3=NULL; //指向P(x)+Q(x) 指针Polyn h4=NULL; //指向P(x)-Q(x) 指针Polyn h5=NULL; //指向P(x)*Q(x) 指针while(1){ num=menu();getchar();switch(num){case 1: //输入第一个多项式,若多项式存在,首先撤消然后再输入if(h1!=NULL){ if(Select("P(x) is not Empty,Create P(x) again?")) { Destroy(h1);h1=Input();}}else h1=Input();break;case 2: //输入第二个多项式,若多项式存在,首先撤消然后再输入if(h2!=NULL){ if(Select("Q(x) is not Empty,Create Q(x) again?")) { Destroy(h2);h2=Input();}}else h2=Input();break;case 3: //两多项式相加if(PolynNotEmpty(h1,"p(x)")&&PolynNotEmpty(h2,"Q(X)"))//判断俩多项式都非空 {h3=AddPolyn(h1,h2);Output(h3,"P(x)+Q(X)");printf("P(x)+Q(x) has finished!\n");getchar();}break;case 4: //两多项式相减if(PolynNotEmpty(h1,"p(x)")&&PolynNotEmpty(h2,"Q(X)")){ h4=SubtractPolyn(h1,h2);Output(h4,"P(x)-Q(x)");printf("P(x)-Q(x) has finished!\n");getchar();}break;case 5: //两多项式相乘if(PolynNotEmpty(h1,"p(x)")&&PolynNotEmpty(h2,"Q(X)")) { h5=MultPolyn(h1,h2);Output(h5,"P(x)*Q(x)");printf("P(x)*Q(x) has finished!\n");getchar();}break;case 6: //显示第一个多项式if(PolynNotEmpty(h1,"p(x)")){ Output(h1,"P(x)");getchar();}break;case 7: //显示第二个多项式if(PolynNotEmpty(h2,"Q(x)")){ Output(h2,"Q(x)");getchar();}break;case 8: //显示相加结果多项式if(PolynNotEmpty(h3,"P(x)+Q(x)")){ Output(h3,"P(x)+Q(x)");getchar();}break;case 9: //显示相减结果多项式if(PolynNotEmpty(h4,"P(x)-Q(x)")){ Output(h4,"P(x)-Q(x)");getchar();}break;case 10: //显示相乘结果多项式if(PolynNotEmpty(h5,"P(x)*Q(x)")){ Output(h5,"P(x)*Q(x)");getchar();}break;case 11: //结束程序运行。

C(语言)程序设计实现多个多项式的加法、减法、乘法

C(语言)程序设计实现多个多项式的加法、减法、乘法

实现多个多项式的加法、减法、乘法发表日期:2003年7月21日出处:mfcer@ 作者:精神病人已经有293位读者读过此文/** 文件名: 1_3.c(选做题)* 实验环境: Turbo C 2.0* 完成时间: 2003年2月22日*-------------------------------------------------------------------- * 改进说明: 可以实现多个多项式的加法、减法、乘法,并且比书中算法更加* 合理. 例如: 连加a+b+c+d,连减a-b-c-d,连乘a*b*c*d.*/#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <string.h>#define TRUE 1#define FALSE 0#define POSITIVE 1#define NEGATIVE -1typedef int status;typedef struct NodeType{float fCoeff;int iExpon;struct NodeType *next;} NodeType, *LinkType;typedef LinkType polynomial;typedef polynomial *PolyPointer;status MakePolyBuff(PolyPointer *, const int);status MakeNode(polynomial *, const float, const int);void AppNodeToList(polynomial *, polynomial); /* 在链表尾追加结点 */status CreatePolyn(PolyPointer, int);status ProcStrError(const char[]); /* 检查输入的数据 */void SortPolyn(PolyPointer, int); /* 根据iExpon域对链表进行升序排序 */void DestroyBuff(PolyPointer, const int);void DestroyPolyn(polynomial);int PolynLength(const polynomial); /* 求链表的长度 */void AddProcess(PolyPointer, const int, PolyPointer, const int); void SubstractProcess(PolyPointer, const int, PolyPointer);void MultiplyProcess(PolyPointer, const int, PolyPointer);void PrintPolyn(const polynomial);void MergePolynCoeff(PolyPointer, int); /* 在有序链表中,合并同类项 */int main(void){int iCounter,iPolyNum; /* 多项式链表缓冲区中链表的个数 */PolyPointer PolyBuff = NULL; /* 用户输入的多项式链表缓冲区 */polynomial PolyAddRes = NULL, /* 存放连加结果链表 */PolySubRes = NULL, /* 存放连减结果链表 */PolyMulRes = NULL; /* 存放连乘结果链表 */char strNum[10];do{printf("请输入需要构造多项式的个数,至少2个: ");gets(strNum);iPolyNum = atoi(strNum);} while (iPolyNum < 2);MakePolyBuff(&PolyBuff, iPolyNum);CreatePolyn(PolyBuff, iPolyNum);SortPolyn(PolyBuff, iPolyNum);MergePolynCoeff(PolyBuff, iPolyNum);printf("\n打印用户输入并整合后的多项式:\n");for (iCounter = 0; iCounter < iPolyNum; iCounter++){printf("第%d个项式:\n", iCounter + 1);PrintPolyn(*(PolyBuff + iCounter));}AddProcess(PolyBuff, iPolyNum, &PolyAddRes, POSITIVE);printf("\n----------------连加结果-----------------\n");PrintPolyn(PolyAddRes);SubstractProcess(PolyBuff, iPolyNum, &PolySubRes);printf("\n----------------连减结果-----------------\n");PrintPolyn(PolySubRes);MultiplyProcess(PolyBuff, iPolyNum, &PolyMulRes);printf("\n----------------连乘结果-----------------\n");PrintPolyn(PolyMulRes);printf("\n运行完毕!\n");/* 回收资源 */DestroyBuff(PolyBuff, iPolyNum);DestroyPolyn(PolyAddRes);DestroyPolyn(PolySubRes);DestroyPolyn(PolyMulRes);getch();return 0;}status MakePolyBuff(PolyPointer *polyBuffHead, const int iPolyNum) {int iCounter;*polyBuffHead = (PolyPointer)malloc(sizeof(polynomial) * iPolyNum);if (!(*polyBuffHead)){printf("错误,内存溢出!\n");return FALSE;}for (iCounter = 0; iCounter < iPolyNum; iCounter++)*(*polyBuffHead + iCounter) = NULL;return TRUE;}status CreatePolyn(PolyPointer PolyBuff, int iPolyNum){int iCounter, iExpon;float fCoeff;char strNum[100], strTemp[64], *cpCurr, *cpCurrNum;polynomial pNewNode = NULL, pInsPos = NULL;printf("\n请输入构造多项式的系数和指数...\n");printf("输入一个多项式的方式为: 系数, 指数; ... ; 系数, 指数;\n例如: 3, 4;5, 6; 7, 8;\n");for (iCounter = 0; iCounter < iPolyNum; iCounter++){printf("\n请输入第%d个多项式:\n", iCounter + 1);gets(strNum);if(!ProcStrError(strNum)) return FALSE;cpCurr = cpCurrNum = strNum;while (*cpCurr != '\0'){if (*cpCurr == ','){strncpy(strTemp, cpCurrNum, cpCurr - cpCurrNum);strTemp[cpCurr - cpCurrNum] = '\0';fCoeff = (float)atof(strTemp);cpCurrNum = cpCurr + 1;}else if (*cpCurr == ';'){strncpy(strTemp, cpCurrNum, cpCurr - cpCurrNum); strTemp[cpCurr - cpCurrNum] = '\0';iExpon = atoi(strTemp);MakeNode(&pNewNode, fCoeff, iExpon);AppNodeToList(PolyBuff + iCounter, pNewNode);cpCurrNum = cpCurr + 1;}cpCurr++;}}return TRUE;}status MakeNode(LinkType *pp, const float coeff, const int expon) {if (!(*pp = (LinkType)malloc(sizeof(NodeType) * 1))){printf("Error, the memory is overflow!\n");return FALSE;}(*pp)->fCoeff = coeff;(*pp)->iExpon = expon;(*pp)->next = NULL;return TRUE;}void AppNodeToList(polynomial *pHead, polynomial pNewNode){static polynomial pCurrNode;if (!(*pHead))(*pHead) = pCurrNode = pNewNode;else{pCurrNode->next = pNewNode;pCurrNode = pCurrNode->next;}}void SortPolyn(PolyPointer PolyBuff, int iPolyNum){int iCounter;polynomial pTemp, pTempCurrNode, /* 临时链表 */pPrevMinExp, pCurrMinExp,/* 指向最小iExpon结点的指针 */ pCurrNode, pPrevNode;for (iCounter = 0; iCounter < iPolyNum; iCounter++){pTemp = NULL;while (*(PolyBuff + iCounter) != NULL){pPrevNode = pPrevMinExp = pCurrMinExp =*(PolyBuff + iCounter);pCurrNode = (*(PolyBuff + iCounter))->next;while (pCurrNode != NULL){if (pCurrMinExp->iExpon > pCurrNode->iExpon){pPrevMinExp = pPrevNode;pCurrMinExp = pCurrNode;}pPrevNode = pCurrNode;pCurrNode = pCurrNode->next;}/* 将系数最小的结点从原链表中取出 */if (pCurrMinExp == *(PolyBuff + iCounter))*(PolyBuff + iCounter) = pPrevMinExp->next;elsepPrevMinExp->next = pCurrMinExp->next;/* 将系数最小的结点插入升序链表 */pCurrMinExp->next = NULL;if (!pTemp)pTemp = pTempCurrNode = pCurrMinExp;else{pTempCurrNode->next = pCurrMinExp;pTempCurrNode = pTempCurrNode->next;}}*(PolyBuff + iCounter) = pTemp;}}void MergePolynCoeff(PolyPointer PolyBuff, int iPolyNum){int iCounter;float MergeCoeffRes = 0;polynomial TempList, ResList = NULL, pCurrNode, pPreNode,pNewNode = NULL;for (iCounter = 0; iCounter < iPolyNum; iCounter++){pPreNode = TempList= *(PolyBuff + iCounter);MergeCoeffRes = pPreNode->fCoeff;pCurrNode = (*(PolyBuff + iCounter))->next;while (pCurrNode != NULL){while ((pCurrNode != NULL) &&(pCurrNode->iExpon == pPreNode->iExpon)){MergeCoeffRes += pCurrNode->fCoeff;pPreNode = pCurrNode;pCurrNode = pCurrNode->next;}/* 在ResList中加入新结点 */if (MergeCoeffRes != 0){MakeNode(&pNewNode, MergeCoeffRes, pPreNode->iExpon); AppNodeToList(&ResList, pNewNode);MergeCoeffRes = 0;}pPreNode = pCurrNode;}DestroyPolyn(TempList);*(PolyBuff + iCounter) = ResList;ResList = NULL;}}void AddProcess(PolyPointer polyBuff, const int iPolyNum,PolyPointer pResult, const int iSign){int iCounter;float fCoeffRes;polynomial pNewNode, pCurrNode_1, pCurrNode_2,pDelList = NULL, /* 下次要删除的中间结果链表 */pResList = NULL; /* 中间结果链表 */pCurrNode_1 = *(polyBuff);for (iCounter = 1; iCounter < iPolyNum; iCounter++){pCurrNode_2 = *(polyBuff + iCounter);while (pCurrNode_1 != NULL && pCurrNode_2 != NULL){if (pCurrNode_1->iExpon == pCurrNode_2->iExpon){fCoeffRes = 0;fCoeffRes = pCurrNode_1->fCoeff +iSign * pCurrNode_2->fCoeff;if (fCoeffRes != 0){MakeNode(&pNewNode, fCoeffRes,pCurrNode_1->iExpon);AppNodeToList(&pResList, pNewNode);}pCurrNode_1 = pCurrNode_1->next;pCurrNode_2 = pCurrNode_2->next;}else if (pCurrNode_1->iExpon < pCurrNode_2->iExpon) {MakeNode(&pNewNode, pCurrNode_1->fCoeff,pCurrNode_1->iExpon);AppNodeToList(&pResList, pNewNode);pCurrNode_1 = pCurrNode_1->next;}else /* 当pCurrNode_1->iExpon > pCurrNode_2->iExpon时候 */{MakeNode(&pNewNode, iSign * pCurrNode_2->fCoeff,pCurrNode_2->iExpon);AppNodeToList(&pResList, pNewNode);pCurrNode_2 = pCurrNode_2->next;}}/* 加入余下的多项式 */while (pCurrNode_1 != NULL){MakeNode(&pNewNode, pCurrNode_1->fCoeff,pCurrNode_1->iExpon);AppNodeToList(&pResList, pNewNode);pCurrNode_1 = pCurrNode_1->next;}while (pCurrNode_2 != NULL){MakeNode(&pNewNode, iSign * pCurrNode_2->fCoeff,pCurrNode_2->iExpon);AppNodeToList(&pResList, pNewNode);pCurrNode_2 = pCurrNode_2->next;}if (pDelList != NULL) DestroyPolyn(pDelList);pCurrNode_1 = pResList;pDelList = pResList;pResList = NULL;}*pResult = pCurrNode_1;}void SubstractProcess(PolyPointer polyBuff, const int iPolyNum,PolyPointer pResult){AddProcess(polyBuff, iPolyNum, pResult , NEGATIVE);}void MultiplyProcess(PolyPointer polyBuff, const int iPolyNum,PolyPointer pResult){int iCounter = 1, jCounter = 0, iLength; /* 缓冲区的长度 */PolyPointer pTempBuff = NULL; /* 存放中间结果的缓冲区 */polynomial pCurrNode_1, pCurrNode_2, pNewNode = NULL;/* 初始化 */pCurrNode_1 = polyBuff[0];iLength = PolynLength(polyBuff[0]);MakePolyBuff(&pTempBuff, iLength);while (TRUE){while (pCurrNode_1 != NULL){pCurrNode_2 = polyBuff[iCounter];while (pCurrNode_2 != NULL){MakeNode(&pNewNode,pCurrNode_1->fCoeff * pCurrNode_2->fCoeff, pCurrNode_1->iExpon + pCurrNode_2->iExpon); AppNodeToList(&pTempBuff[jCounter], pNewNode);pCurrNode_2 = pCurrNode_2->next;}jCounter++;pCurrNode_1 = pCurrNode_1->next;}/* 回收旧的中间结果 */if (pResult != NULL) DestroyPolyn(*pResult);/* 获得新的中间结果 */AddProcess(pTempBuff, iLength, pResult , POSITIVE);DestroyBuff(pTempBuff, iLength); /* 回收存中间结果的缓冲区 */jCounter = 0;if (++iCounter >= iPolyNum)break;else{iLength = PolynLength(*pResult);MakePolyBuff(&pTempBuff, iLength);pCurrNode_1 = *pResult;}}}void PrintPolyn(const polynomial polyList){polynomial pCurrNode = polyList;printf("多项式的长度为: %d\n", PolynLength(polyList));while (pCurrNode != NULL){printf("%.2fX^%d", pCurrNode->fCoeff, pCurrNode->iExpon); if (pCurrNode->next != NULL)if (pCurrNode->next->fCoeff > 0 )printf("+");pCurrNode = pCurrNode->next;}printf("\n");}int PolynLength(const polynomial polyList){int iLength = 0;polynomial pCurrNode = polyList;while (pCurrNode != NULL){pCurrNode = pCurrNode->next;iLength++;}return iLength;}void DestroyBuff(PolyPointer polyBuff, const int iPolyNum){int iCounter;for (iCounter = 0; iCounter < iPolyNum; iCounter++)DestroyPolyn(polyBuff[iCounter]);free(polyBuff);}void DestroyPolyn(polynomial polyList){polynomial pCurrNode;while (polyList != NULL){pCurrNode = polyList;polyList = polyList->next;free(pCurrNode);}}status ProcStrError(const char str[]){const char *cpCurr = str;if (!strlen(str)){printf("你没有输入数据!\n");return FALSE;}while (*cpCurr != '\0'){if (!(*cpCurr == ' ' || *cpCurr == ',' || *cpCurr == ';' || *cpCurr == '-')&& ('0' > *cpCurr || *cpCurr > '9')|| (*(cpCurr + 1) == '\0' && *cpCurr != ';')){printf("输入数据出错,请注意正确的输入方式!\n");return FALSE;}cpCurr++;}return TRUE;}。

多项式加法_C语言程序设计(第2版)_[共2页]

多项式加法_C语言程序设计(第2版)_[共2页]

232调试这两个函数的方法和【例10-7】、【例10-8】一样,请大家自己试试。

10.2.2 多项式加法【例10-13】两个多项式相加运算。

1.问题描述编写程序实现变量为x、y、z的两个整系数多项式的相加。

其中,变量x、y、z的指数大于等于0小于等于9。

2.思路分析(1)确定数据结构。

①用一个循环链表表示多项式,链表的每个结点表示多项式的一项,格式如下。

coef index next它表示项coefx i y j z k,其中coef表示项系数;index=100i+10j+k(i,j,k皆为整数,且0≤i,j,k≤9),表示指数;next为指向下一个结点的指针。

这样表示,可以简化多项式按指数排序操作。

②链表中设置了一个表头结点,其值如下。

0 −1 next其中,next指向多项式的首项。

③链表中其余结点按index值的降序排列。

例如,多项式3x6−5x5y2+6可表示如下。

0 −1 3 600 −5520 6 −0 Λ(2)确定程序结构。

①定义函数blist用于创建一个循环链表,表示一个多项式。

②定义函数polyadd(Node *p)用于将p所指多项式加到q所指多项式中,实现两个多项式的相加。

③定义函数Printlist(Node *h)用于输出h所指循环链表中的多项式。

④定义函数Freelist(Node *h)用于释放h所指循环链表占用的堆内存。

更多细节参考源程序中的注释。

3.程序实现#include<stdio.h>#include<stdlib.h>typedef struct node{int coef,index;struct node *next;}Node;int main(void){Node *p,*q;Node *Createlist(void);void Polyadd(Node *,Node *);void Printlist(Node *);void Freelist(Node *);p=Createlist( );。

多项式的加法和乘法计算c语言代码

多项式的加法和乘法计算c语言代码

多项式的加法和乘法计算C语言代码多项式是代数学中常见的一种数学表达式形式,通常表示为:P(x) = a0 + a1*x + a2*x^2 + a3*x^3 + ... + an*x^n其中a0, a1, a2,...,an是多项式P(x)的系数,x是变量,n是多项式的次数。

在实际的编程开发中,我们经常需要实现多项式的加法和乘法计算。

下面我们将介绍如何使用C语言来实现多项式的加法和乘法计算。

一、多项式的表示与存储在C语言中,可以使用结构体来表示多项式,并使用数组来存储多项式的系数。

假设我们要表示一个最高次数为n的多项式,可以定义结构体如下:```ctypedef struct {int coeff[MAX_SIZE]; // 存储多项式系数的数组int degree; // 多项式的最高次数} Polynomial;其中MAX_SIZE是一个常数,用来表示多项式的最大阶数。

在实际使用中,可以根据需要进行调整。

二、多项式的加法多项式的加法实质上是将两个多项式的对应系数相加,并将结果存储在一个新的多项式中。

下面是多项式加法的C语言代码实现:```cPolynomial addPolynomial(Polynomial poly1, Polynomial poly2) {Polynomial result;int i;// 确定结果多项式的最高次数result.degree = (poly1.degree > poly2.degree) ?poly1.degree : poly2.degree;// 将对应系数相加for (i = 0; i <= result.degree; i++) {result.coeff[i] = poly1.coeff[i] + poly2.coeff[i];return result;}```以上代码通过遍历多项式的系数数组,将对应位置的系数相加,并将结果存储在result中。

c语言多项式加法

c语言多项式加法

c语言多项式加法C语言是一种广泛应用于编程领域的高级编程语言,它具有灵活性和强大的功能。

在C语言中,多项式加法是一个常见的操作,用于将两个多项式相加得到一个新的多项式。

本文将介绍C语言中多项式加法的实现方法和相关技巧。

多项式是数学中常见的一种表达方式,它由若干项组成,每一项包含一个系数和一个指数。

多项式加法的基本原理是将两个多项式的对应项相加,得到一个新的多项式。

在C语言中,可以使用结构体来表示多项式。

结构体中包含两个成员变量,一个表示系数,一个表示指数。

通过定义一个结构体数组,可以方便地表示一个多项式。

我们需要定义一个结构体来表示多项式的每一项:```cstruct term {int coefficient; // 系数int exponent; // 指数};```接下来,我们可以定义一个函数来实现多项式加法的操作。

该函数接受两个多项式作为参数,并返回一个新的多项式作为结果。

```cstruct term* addPolynomials(struct term* poly1, int size1, struct term* poly2, int size2, int* resultSize) {int maxSize = size1 + size2;struct term* result = (struct term*)malloc(maxSize * sizeof(struct term));int i = 0, j = 0, k = 0;while (i < size1 && j < size2) {if (poly1[i].exponent > poly2[j].exponent) {result[k++] = poly1[i++];} else if (poly1[i].exponent < poly2[j].exponent) {result[k++] = poly2[j++];} else {result[k].coefficient = poly1[i].coefficient + poly2[j].coefficient;result[k].exponent = poly1[i].exponent;i++;j++;k++;}}// 将剩余的项添加到结果中while (i < size1) {result[k++] = poly1[i++];}while (j < size2) {result[k++] = poly2[j++];}*resultSize = k;return result;}```上述函数使用了两个指针i和j来分别遍历两个多项式的项,同时使用一个指针k来指向结果多项式的当前位置。

数据结构多项式运算的程序(加减法和乘法)C语言版

数据结构多项式运算的程序(加减法和乘法)C语言版

数据结构多项式运算的程序(加减法和乘法)C语言版#include#includetypedef struct node{//定义节点类型float coef;int expn;struct node * next;}PLOY;void start()//用户选择界面{printf("************************************\n");printf(" 两个一元多项式的相加/相减,相乘:\n");printf("************************************\n");printf("请选择操作:\n");printf("0.退出\n");printf("1.两个一元多项式相加\n");printf("2.两个一元多项式相乘\n");printf("3.两个一元多项式相减\n");}void insert(PLOY *head,PLOY *inpt)//查找位置插入新链节程序{PLOY *pre,*now;int signal=0;pre=head;//pre定义为现在的前一个链节if(pre->next==NULL) {pre->next=inpt;}else {now=pre->next;while(signal==0){if(inpt->expnexpn)//当新链节小于现在的连接时向后移一个链节{if(now->next==NULL){now->next=inpt;signal=1;}else{pre=now;now=pre->next;}}elseif(inpt->expn>now->expn)//如果发现比现在的链节大了就插入到这个连接的前面{inpt->next=now;pre->next=inpt;signal=1;}else{now->coef=now->coef+inpt->coef;signal=1;free(inpt);//与当前链节相等指数if(now->coef==0){pre->next=now->next;free(now);}}}}}PLOY *creat(char ch)//输入多项式{PLOY *head,*inpt;float x;int y;head=(PLOY *)malloc(sizeof(PLOY));//创建链表头head->next=NULL;printf("请输入一元多项式%c:(格式是:系数指数;以0 0 结束!)\n",ch);scanf("%f %d",&x,&y);while(x!=0){inpt=(PLOY *)malloc(sizeof(PLOY));//创建新链节inpt->coef=x;inpt->expn=y;inpt->next=NULL;insert(head,inpt);//不然就查找位置并且插入新链节printf("请输入一元多项式%c的下一项:(以0 0 结束!)\n",ch);scanf("%f %d",&x,&y);}return head;}PLOY *addPLOY(PLOY *head,PLOY *pre)//多项式相加{PLOY *inpt;int flag=0;while(flag==0){if(pre->next==NULL)flag=1;//当现在指向空时跳出循环else{pre=pre->next;inpt=(PLOY *)malloc(sizeof(PLOY));//创建新链节inpt->coef=pre->coef;inpt->expn=pre->expn;inpt->next=NULL;insert(head,inpt);}//否则把当前"g(x)"的链节插入到"y(x)"中}return head;}PLOY *minusPLOY(PLOY *head,PLOY *pre)//多项式相加{PLOY *inpt;int flag=0;while(flag==0){if(pre->next==NULL)flag=1;//当现在指向空时跳出循环else{pre=pre->next;inpt=(PLOY *)malloc(sizeof(PLOY));//创建新链节inpt->coef=0-pre->coef;inpt->expn=pre->expn;inpt->next=NULL;insert(head,inpt);}//否则把当前"g(x)"的链节插入到"y(x)"中}return head;}PLOY *byPLOY(PLOY *head1,PLOY *head2)//多项式相乘{PLOY *inpt,*res,*pre;int flag=0;res=(PLOY *)malloc(sizeof(PLOY));//创建链表头res->next=NULL;head1=head1->next;pre=head2;while(flag==0){if(pre->next==NULL){pre=head2;//当现在指向空时跳出循环head1=head1->next;continue;}if(head1==NULL){flag=1;//当现在指向空时跳出循环continue;}pre=pre->next;inpt=(PLOY *)malloc(sizeof(PLOY));//创建新链节inpt->coef=pre->coef*head1->coef;inpt->expn=pre->expn+head1->expn;inpt->next=NULL;insert(res,inpt);//把当前"g(x)"的链节插入到"y(x)"中}return res;}void print(PLOY *fun)//输出多项式{PLOY *printing;int flag=0;printing=fun->next;//正在被打印的链节if(fun->next==NULL)//如果函数为空打印0{printf("0\n");return;}while(flag==0){if(printing->coef>0&&fun->next!=printing) printf("+");//为正数时打印"+"号if(printing->coef==1);//如果为"1"就不用打印系数了else if(printing->coef==-1)printf("-");//如果为"-1"就打印"-"号就行了elseprintf("%f",printing->coef);//其余情况都得打印if(printing->expn!=0) printf("x^%d",printing->expn);//如果指数为"0"不打印指数项else if((printing->coef==1)||(printing->coef==-1))printf("1");if(printing->next==NULL)flag=1;//如果现在的链节没有下一个就结束elseprinting=printing->next;}printf("\n");}void main(){PLOY *f,*g;int sign=-1;//设置标志start();while(sign!=0){scanf("%d",&sign);switch(sign){case 0:break;//退出case 1:printf("你选择的操作是多项式相加:\n"); f=creat('f');//输入多项式f(x)printf("f(x)=");print(f);g=creat('g');//输入多项式g(x)printf("g(x)=");print(g);printf("F(x)=f(x)+g(x)=");f=addPLOY(f,g);//两个多项式相加print(f);sign=-1;//复位标志start();//回复用户选择界面break;}case 2:{printf("你选择的操作是多项式相乘:\n"); f=creat('f');//输入多项式f(x)printf("f(x)=");print(f);g=creat('g');//输入多项式g(x)printf("g(x)=");print(g);printf("F(x)=f(x)*g(x)=");f=byPLOY(f,g);//两个多项式相加print(f);sign=-1;//复位标志start();//回复用户选择界面break;case 3:{printf("你选择的操作是多项式相减:\n");f=creat('f');//输入多项式f(x)printf("f(x)=");print(f);g=creat('g');//输入多项式g(x)printf("g(x)=");print(g);printf("F(x)=f(x)-g(x)=");f=byPLOY(f,g);//两个多项式相加print(f);sign=-1;//复位标志start();//回复用户选择界面break;}default:{printf("输入有误!请重新选择操作!\n");//选择错误,返回选择界面start();break;}}}}。

一元多项式相加C语言代码

一元多项式相加C语言代码

数据结构作业一元多项式相加C语言代码#include<stdio.h>#include<malloc.h>typedef struct node{int exp,coef;struct node *link;}PolyNode,*Polylinklist;Polylinklist Creat(int n){Polylinklist p,r=NULL,list=NULL;int coef,exp,i;for(i=1;i<=n;i++){scanf("%d %d",&coef,&exp);p=(Polylinklist)malloc(sizeof(PolyNode));p->coef=coef;p->exp=exp;p->link=NULL;if(list==NULL)list=p;elser->link=p;r=p;}return(list);}Polylinklist ATTACH(int coef,int exp,Polylinklist r){Polylinklist w;w=(Polylinklist)malloc(sizeof(PolyNode));w->exp=exp;w->coef=coef;r->link=w;return w;}Polylinklist PADD(Polylinklist a,Polylinklist b){Polylinklist c;Polylinklist r,p=a,q=b;int x;c=(Polylinklist)malloc(sizeof(PolyNode));r=c;while(p!=NULL&&q!=NULL)if(p->exp==q->exp){x=p->coef+q->coef;if(x!=0)r=ATTACH(x,q->exp,r);p=p->link;q=q->link;}else if(p->exp<q->exp){r=ATTACH(q->coef,q->exp,r);q=q->link;}else {r=ATTACH(p->coef,p->exp,r);p=p->link;}while(p!=NULL){r=ATTACH(p->coef,p->exp,r);p=p->link;}while(q!=NULL){r=ATTACH(q->coef,q->exp,r);q=q->link;}r->link=NULL;p=c;c=c->link;free(p);return c;}void Result(Polylinklist w){Polylinklist m;m=w;while(w==NULL){printf("0");break;}while(w!=NULL){if(w->exp==0)printf("%d",w->coef);elseprintf("%d*x^%d",w->coef,w->exp);w=w->link;while(w!=NULL){if(w->coef>0){if(w->exp==0)printf("+%d",w->coef);elseprintf("+%d*x^%d",w->coef,w->exp);}else{if(w->exp!=0)printf("%d*x^%d",w->coef,w->exp);elseprintf("%d",w->coef);}w=w->link;}}}void main(){Polylinklist c=NULL;PolyNode *Lengtha;PolyNode *Lengthb;int a1,b1;printf("Please input a's Length:");scanf("%d",&a1);Lengtha=Creat(a1);printf(" a=");Result(Lengtha);printf("\n");printf("Please input b's Length:");scanf("%d",&b1);Lengthb=Creat(b1);printf(" b=");Result(Lengthb);printf("\n");c=PADD(Lengtha,Lengthb);printf("\n");printf(" c=");Result(c);printf("\n");}。

数据结构(C语言)-案例分析(顺序表实现多项式运算)

数据结构(C语言)-案例分析(顺序表实现多项式运算)

数据结构(C语⾔)-案例分析(顺序表实现多项式运算)顺序表实现多项式运算//多项式基本运算#include"stdio.h"#include"stdlib.h"#define MAX 100typedef int Data;typedef struct{Data data[MAX];int Length;}SeqList;SeqList A;SeqList B;SeqList C;void InitList(SeqList *A,SeqList *B,SeqList *C){A->Length=0;B->Length=0;C->Length=0;}void CreateList(SeqList *A,SeqList *B,int n,int x){int i;printf("输⼊多项式A的系数:");for(i=0;i<n;i++){scanf("%d",&A->data[i]);}A->Length=i;printf("\n输⼊多项式B的系数:");for(i=0;i<x;i++){scanf("%d",&B->data[i]);}B->Length=i;printf("\n多项式A的系数:");for(i=0;i<A->Length;i++){printf("%3d",A->data[i]);}printf("\n多项式B的系数:");for(i=0;i<B->Length;i++){printf("%3d",B->data[i]);}}void Addition(SeqList *A,SeqList *B,SeqList *C){int i;if(A->Length>B->Length){C->Length=A->Length;for(i=0;i<A->Length;i++){if(i!=B->Length){C->data[i]=A->data[i]+B->data[i];}else{C->data[i]=A->data[i];}}}else if(B->Length>A->Length){C->Length=B->Length;for(i=0;i<B->Length;i++){if(i!=A->Length){C->data[i]=A->data[i]+B->data[i];}else{C->data[i]=B->data[i];}C->Length=A->Length;for(i=0;i<A->Length;i++){C->data[i]=A->data[i]+B->data[i];}}printf("A+B得:");for(i=0;i<C->Length;i++){printf("%3d",C->data[i]);}}void Division(SeqList *A,SeqList *B,SeqList *C){int i;if(A->Length>B->Length){C->Length=A->Length;for(i=0;i<A->Length;i++){if(i!=B->Length){C->data[i]=A->data[i]/B->data[i];}else{C->data[i]=A->data[i];}}}else if(B->Length>A->Length){C->Length=B->Length;for(i=0;i<B->Length;i++){if(i!=A->Length){C->data[i]=A->data[i]/B->data[i];}else{C->data[i]=B->data[i];}}}else{C->Length=A->Length;for(i=0;i<A->Length;i++){C->data[i]=A->data[i]/B->data[i];}}printf("A/B得:");for(i=0;i<C->Length;i++){printf("%3d",C->data[i]);}}void Multiplication(SeqList *A,SeqList *B,SeqList *C){ int i;if(A->Length>B->Length){C->Length=A->Length;for(i=0;i<A->Length;i++){if(i!=B->Length){C->data[i]=A->data[i]*B->data[i];}else{C->data[i]=A->data[i];}}}else if(B->Length>A->Length){C->Length=B->Length;for(i=0;i<B->Length;i++){if(i!=A->Length){C->data[i]=A->data[i]*B->data[i];}else{C->data[i]=B->data[i];C->Length=A->Length;for(i=0;i<A->Length;i++){C->data[i]=A->data[i]*B->data[i];}}printf("A*B得:");for(i=0;i<C->Length;i++){printf("%3d",C->data[i]);}}void Menu(){printf("\n 多项式计算");printf("\n--------------------------------------");printf("\n 1--创建多项式 ");printf("\n 2--加法计算 ");printf("\n 3--除法计算 ");printf("\n 4--乘法计算 ");printf("\n 0--退出 ");printf("\n--------------------------------------");printf("\n请输⼊菜单号(0-4):");}int main(){SeqList A;SeqList B;SeqList C;int n,x,loc;char ch1,ch2,a;ch1='y';while(ch1=='y'||ch1=='Y'){Menu();scanf("%c",&ch2);getchar();switch(ch2){case'1':InitList(&A,&B,&C);printf("输⼊第⼀个多项式系数的个数:");scanf("%d",&n);printf("输⼊第⼆个多项式系数的个数:");scanf("%d",&x);CreateList(&A,&B,n,x);break;case'2':Addition(&A,&B,&C);break;case'3':Division(&A,&B,&C);break;case'4':Multiplication(&A,&B,&C);break;case'0':ch1='n';break;default:printf("输⼊有误");}if(ch2!='0'){printf("\n按回车键继续,按任意键返回主菜单!\n"); a=getchar();if(a!='\xA'){getchar();}。

多项式相加(含运行结果截图)

多项式相加(含运行结果截图)
while (r){
printf("指数:%d系数:%f\n",r->expn,r->coef);
r=r->next;
}
}
main()
{
void creatpolyn(struct linklist *p,int n); //输入n项的系数,建立一个链表
struct linklist * addpolyn(struct linklist*p,struct linklist*q); //两个多项式相加,返回结果指针
la->coef=s; //此项不为0需要修改la中当前节点的系数值
la=la->next;
p=p->next;
lb=lb->next;
q=q->next;
}
else {
p->next=la->next;
r=la;
la=la->next;
free(r);
lb=lb->next;
q=q->next;
}
scanf("%d",&n);
creatpolyn(p,n);
printf("请输入第二个多项式的项数:\n");
scanf("%d",&n);
creatpolyn(q,n);
r=addpolyn(p,q);
print(r);
}
四.算法分析
多项式由系数和指数组成,建立两个链表分别存储系数和指数。为了方便实验过程,实验在输入的时候按照指数的由低到高输入,避免了排序。在相加过程中,将两个链表从头到尾进行比较,直到比到一个链表没有元素为止,将其中指数相同的系数进行加减运算。最后打印出多项式。

小白专场-多项式乘法与加法运算-c语言实现

小白专场-多项式乘法与加法运算-c语言实现

⼩⽩专场-多项式乘法与加法运算-c语⾔实现⽬录数据结构与算法_Python_C完整教程⽬录:⼀、题意理解设计函数分别求两个⼀元多项式的乘积与和,例:\[\text{已知以下两个多项式:} \\ \begin{align} & 3x^4-5x^2+6x-2 \\ & 5x^{20}-7x^4+3x \end{align} \]\[\text{多项式和为:} \\ \begin{align} 5x^{20}-4x^4-5x^2+9x-2 \end{align} \]假设多项式的乘积为\((a+b)(c+d)=ac+ad+bc+bd\),则多项式的乘积如下:\[\begin{align} 15x^{24}-25x^{22}+30x^{21}-10x^{20}-21x^8+35x^6-33x^5+14x^4-15x^3+18x^2-6x \end{align} \]通过上述题意理解,我们可以设计函数分别求两个⼀元多项式的乘积与和。

输⼊样例:\[\begin{align} & 3x^4-5x^2+6x-2 \quad --> \quad \text{4个}\,3\,4\,-5\,2\,6\,1\,-2\,0 \\ & 5x^{20}-7x^4+3x \quad --> \quad \text{3个}\,5\,20\,-7\,4\,3\,1 \\ \end{align} \\ \]输出样例:\[\begin{align} & 15x^{24}-25x^{22}+30x^{21}-10x^{20}-21x^8+35x^6-33x^5+14x^4-15x^3+18x^2-6x \\ & 15 \, 24 \, -25 \, 22 \, 30 \, 21 \, -10 \, 20 \, -21 \, 8 \, 35 \, 6 \, -33 \, 5 \, 14 \, 4 \, -15 \, 3 \, 18 \, 2 \, -6 \, 1 \, 5 \, 20 \, -4 \, 4 \, -5 \, 2 \, 9 \, 1 \, -2 \, 0 \end{align} \]⼆、求解思路多项式表⽰程序框架读多项式加法实现乘法实现多项式输出三、多项式的表⽰仅表⽰⾮零项3.1 数组优点:编程简单、调试简单缺点:需要事先确定数组⼤⼩⼀种⽐较好的实现⽅法是:动态数组(动态更改数组的⼤⼩)3.2 链表优点:动态性强缺点:编程略为复杂、调试⽐较困难数据结构设计:/* c语⾔实现 */typedef struct PolyNode *Polynomial;struct PolyNode{int coef;int expon;Polynomial link;}四、程序框架搭建/* c语⾔实现 */int main(){读⼊多项式1;读⼊多项式2;乘法运算并输出;加法运算并输出;return 0;}int main(){Polynomial P1, P2, PP, PS;P1 = ReadPoly();P2 = ReadPoly();PP = Mult(P1, P2);PrintPoly(PP);PS = Add(P1, P2);PrintPoly(PS);return 0;}需要设计的函数:读⼀个多项式两多项式相乘两多项式相加多项式输出五、如何读⼊多项式/* c语⾔实现 */Polynomial ReadPoly(){...;scanf("%d", &N);...;while (N--) {scanf("%d %d", &c, &e);Attach(c, e, &Rear);}...;return P;}Rear初值是多少?两种处理⽅法:Rear初值为NULL:在Attach函数中根据Rear是否为NULL做不同处理Rear指向⼀个空结点/* c语⾔实现 */void Attach(int c, int e, Polynomial *pRear){Polynomial P;P = (Polynomial)malloc(sizeof(struct PolyNode));p->coef = c; /* 对新结点赋值 */p->expon = e;p->link = NULL;(*pRear)->link = P;(*pRear) = P; /* 修改pRear值 *//* c语⾔实现 */Polynomial ReadPoly(){Polynomial P, Rear, t;int c, e, N;scanf("%d", &N);P = (Polynomial)malloc(sizeof(struct PolyNode)); // 链表头空结点 P->link = NULL;Rear = P;while (N--) {scanf("%d %d", &c, &e);Attach(c, e, &Rear); // 将当前项插⼊多项式尾部}t = P; P = P->link; free(t); // 删除临时⽣成的头结点return P;}六、如何将两个多项式相加/* c语⾔实现 */Polynomial Add(Polynomial P1, Polynomial P2){...;t1 = P1; t2 = P2;P = (Polynomial)malloc(sizeof(struct PolyNode));P->link = NULL;Rear = P;while (t1 && t2){if (t1->expon == t2->expon){...;}else if (t1->expon > t2->expon){...;}else{...;}}while (t1){...;}while (t2){...;}...;return P;}七、如何将两个多项式相乘⽅法:将乘法运算转换为加法运算将P1当前项(ci, ei)乘P2多项式,再加到结果多项式⾥/* c语⾔实现 */t1 = P1; t2 = P2;P = (Polynomial)malloc(sizeof(struct PolyNode)); P->link = NULL;Rear = P;while (t2){Attach(t1->coef * t2->coef, t1->expon + t2->expon, &Rear);t2 = t2->link;}逐项插⼊将P1当前项(c1_i, e1_i)乘P2当前项(c2_i, e2_i),并插⼊到结果多项式中。

多项式相加的函数(数据结构_C语言版)

多项式相加的函数(数据结构_C语言版)

多项式相加的函数(数据结构_C语言版)一、编写一个程序用单链表存储多项式,并实现两个多项式相加的函数。

【源程序】#include#include#define MAX 20typedef struct{ float coef;int exp;}PolyArray[MAX];typedef struct pnode{ float coef;//系数int exp;//指数struct pnode *next;}PolyNode;void DispPoly(PolyNode *L)//输出多项式{ PolyNode *p=L->next;while(p!=NULL){ printf("%gx^%d",p->coef,p->exp);p=p->next;}printf("\n");}void CreateListR(PolyNode *&L,PolyArray a,int n)//尾插法建立单链表{ PolyNode *s,*r;int i;L=(PolyNode *)malloc(sizeof(PolyNode)); //创建头结点L->next=NULL;r=L; //r始终指向终端结点,开始时指向头结点for (i=0;i<n;i++)< p="">{s=(PolyNode *)malloc(sizeof(PolyNode));//创建新结点s->coef=a[i].coef;s->exp=a[i].exp;r->next=s; //将*s插入*r之后r=s;}r->next=NULL;}void Sort(PolyNode *&head)//按exp域递减排序{ PolyNode *p=head->next,*q,*r;if(p!=NULL){ r=p->next;p->next=NULL;p=r;while(p!=NULL){ r=p->next;q=head;while(q->next!=NULL&&q->next->exp>p->exp)q=q->next;p->next=q->next;q->next=p;p=r;}}}void Add(PolyNode *ha,PolyNode *hb,PolyNode *&hc)//求两个有序集合的并{PolyNode *pa=ha->next,*pb=hb->next,*s,*tc;float c;hc=(PolyNode *)malloc(sizeof(PolyNode));tc=hc;while(pa!=NULL&&pb!=NULL){ if(pa->exp>pb->exp){ s=(PolyNode *)malloc(sizeof(PolyNode)); //复制结点s->exp=pa->exp;s->coef=pa->coef;tc->next=s;tc=s;pa=pa->next;}else if(pa->expexp){ s=(PolyNode *)malloc(sizeof(PolyNode)); //复制结点s->exp=pb->exp;s->coef=pb->coef;tc->next=s;tc=s;pb=pb->next;}else{ c=pa->coef+pb->coef;if(c!=0)//系数之和不为0事创建新结点{ s=(PolyNode *)malloc(sizeof(PolyNode));s->exp=pa->exp;s->coef=c;tc->next=s;tc=s;}pa=pa->next;pb=pb->next;}}if(pb!=NULL)pa=pb;//复制余下的结点while(pa!=NULL){ s=(PolyNode *)malloc(sizeof(PolyNode)); //复制结点s->exp=pa->exp;s->coef=pa->coef;tc->next=s;tc=s;pa=pa->next;}tc->next=NULL;}void main(){PolyNode *ha,*hb,*hc;PolyArray a={{1.5,0},{2.5,1},{3.3,3},{-2.5,5}};PolyArray b={{-1.5,0},{2.5,1},{3.7,3},{-2.5,5},{5.6,7}};CreateListR(ha,a,4);CreateListR(hb,b,5);printf("原多项式A为:");DispPoly(ha);printf("原多项式B为:");DispPoly(hb);Sort(ha);Sort(hb);printf("有序多项式A:");DispPoly(ha);printf("有序多项式B:");DispPoly(hb);Add(ha,ha,hc);printf("多项式相加结果:");DispPoly(hc); printf("\n");}</n;i++)<>。

C语言 多项式的加减

C语言 多项式的加减

多项式的加减详细设计#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct term{ //多项式结点的定义float coef; //系数int exp; //指数struct term *link; //链接指针}*Poly;void Input(Poly &pl) //输入多项式{term *nterm,*p,*pre;float c;int e;pl=new term; //pl为头指针pl->link=NULL;printf("***当输入指数<0时结束,且不进入运算***\n");while(1){printf("请输入系数和指数\n");scanf("%f%d",&c,&e);if(e<0)break; //循环结束条件nterm=new term; //开辟新结点if(!nterm) //验证是否开辟到{printf("error");exit(1);}nterm->coef=c;nterm->exp=e;nterm->link=NULL;int g=0;pre=pl;if(pl->link==NULL) //加入第一个结点pl->link=nterm;else //加入第二及以后的结点{p=pre->link;while(g==0){if( p->exp<nterm->exp){if(p->link==NULL){p->link=nterm;g=1;}else{pre=p;p=pre->link;}//向后推进}elseif( p->exp>nterm->exp){nterm->link=p;pre->link=nterm;g=1;}else //指数相等的项的系数相加{ p->coef=p->coef+nterm->coef;g=1;delete nterm;if(p->coef==0)//节点的系数为0时,删除{pre->link=p->link;delete p;}}}}}}void Output(Poly &pl) //输出多项式{term *p=pl->link;printf("输出多项式为:");int h=0;while(!h){if(pl->link!=p && p->coef>0)//最初不输出+号printf("+");printf("%0.1f",p->coef);switch(p->exp)//输出指数格式{case 0:break;case 1:printf("X");break;default :printf("X^");printf("%d",p->exp);}if(p->link==NULL)//循环结束条件h=1;elsep=p->link;}printf("\n");}void Add(Poly &A, Poly &B, Poly &C ,int Q) //多项式加减//两个一元多项式链表的头结点分别是A,B,相加减结果为C {term *pa,*pb,*pc,*p,*s;float temp;C=new term;C->link=NULL;pc=C;pa=A->link;pb=B->link;while(pa!=NULL && pb!=NULL)//pa,pb都存在时{s=new term;if(!s){printf("error");exit(1);}if(pa->exp==pb->exp) //系数相等{if(Q==1) //多项式相加temp=pa->coef+pb->coef;else //多项式相减if(pa->coef>pb->coef)temp=pa->coef-pb->coef;elsetemp=pb->coef-pa->coef;if(temp>0){pc->link=s;pc=pc->link;pc->coef=temp;pc->exp=pa->exp;}else//加减后的系数为0,删除delete s;pa=pa->link;pb=pb->link;}else //系数不相等if(pa->exp<pb->exp){pc->link=s;pc=pc->link;pc->coef=pa->coef;pc->exp=pa->exp;pa=pa->link;}else{pc->link=s;pc=pc->link;pc->coef=pb->coef;pc->exp=pb->exp;pb=pb->link;}}p=(pa?pa:pb);//P指向剩余链表的地址while(p!=NULL)//剩余结点原样输入{pc->link=new term;if(!pc->link){printf("error");exit(1);}pc=pc->link;pc->coef=p->coef;pc->exp=p->exp;p=p->link;}pc->link=NULL;}void main(){Poly pa,pb,pc;printf("\n");printf("//**此程序可以实现两个多项式的加减**//\n");printf("*****输入第一个多项式*****:\n");Input(pa);Output(pa);printf("\n");printf("\n");printf("*****输入第二个多项式*****:\n");Input(pb);Output(pb);int Q;printf("/////////请选择操作/////////\n");printf("********1:两多项式相加*******\n");printf("********2:两多项式相减*******\n");scanf("%d",&Q);Add(pa,pb,pc,Q);printf("你所需要的结果是:\n");Output(pc);}测试结果。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

多项式加法
#include <stdio.h>
#include <stdlib.h>
#define Max_Size 100
typedef struct node
{
float coef;
int expn;
struct node *next;
}PolyNode;
int CreCoeStr(float C[])
{
char flag;
int i=0;
do
{
scanf("%f",&C[i++]);
scanf("%c",&flag);
} while (flag!='#');
return(i);
}
void CreExpStr(int E[])
{
int i=0;
char flag;
do
{
scanf("%d",&E[i++]);
scanf("%c",&flag);
} while (flag!='#');
}
void InitPolyList(PolyNode **sq)
{
if((*sq=(PolyNode *)malloc(sizeof(PolyNode)))==NULL) exit(1);
(*sq)->next=NULL;
}
void CreatPolyList(PolyNode **sq,float C[],int E[],int num)
{
int i;
PolyNode *s,*r=*sq;
for(i=0;i<num;i++)
{
if((s=(PolyNode *)malloc(sizeof(PolyNode)))==NULL) exit(1);
s->coef=C[i];
s->expn=E[i];
r->next=s;
r=s;
}
r->next=NULL;
}
void InsertSortPoly(PolyNode **sq)
{
PolyNode *p,*q,*r,*u;
p=(*sq)->next;
(*sq)->next=NULL;
while (p)
{
r=*sq;
q=(*sq)->next;
while (q&&q->expn<=p->expn)
{
r=q;
q=q->next;
}
u=p->next;
p->next=r->next;
r->next=p;
p=u;
}
}
void DispList(PolyNode *sq)
{
PolyNode *p=sq->next;
while(p)
{
printf("(%7.2f,%d)",p->coef,p->expn);
p=p->next;
}
printf("\n");
}
PolyNode *AddPoly(PolyNode *sq_a,PolyNode *sq_b)
{
PolyNode *p_1=sq_a->next,*p_2=sq_b->next,*tc,*p,*s,*pc;
InitPolyList(&pc);
tc=pc;
while (p_1&&p_2)
{
if(p_1->expn<p_2->expn)
{
if((s=(PolyNode *)malloc(sizeof(PolyNode)))==NULL) exit(1);
s->coef=p_1->coef;
s->expn=p_1->expn;
s->next=NULL;
tc->next=s;
tc=s;
p_1=p_1->next;
}
else if(p_1->expn>p_2->expn)
{
if((s=(PolyNode *)malloc(sizeof(PolyNode)))==NULL) exit(1);
s->coef=p_2->coef;
s->expn=p_2->expn;
s->next=NULL;
tc->next=s;
tc=s;
p_2=p_2->next;
}
else
{
if(p_1->coef+p_2->coef)
{
if((s=(PolyNode *)malloc(sizeof(PolyNode)))==NULL) exit(1);
s->coef=p_1->coef+p_2->coef;
s->expn=p_1->expn;
s->next=NULL;
tc->next=s;
tc=s;
}
p_1=p_1->next;
p_2=p_2->next;
}
}
if(p_1) p=p_1;
else p=p_2;
while (p)
{
if((s=(PolyNode *)malloc(sizeof(PolyNode)))==NULL) exit(1);
s->coef=p->coef;
s->expn=p->expn;
tc->next=s;
tc=s;
p=p->next;
}
tc->next=NULL;
return pc;
}
void main()
{
PolyNode *sq_1,*sq_2,*sq_3;
float C_1[Max_Size],C_2[Max_Size];
int E_1[Max_Size],E_2[Max_Size],num_1,num_2;
printf("\n\t\t两个多项式相加运算\n");
printf("\n");
printf("\n");
printf("请输入多项式A 的各项系数(以‘#’结束): ");
num_1=CreCoeStr(C_1);
printf("\n请输入多项式A 的各项幂数(以‘#’结束): ");
CreExpStr(E_1);
printf("\n请输入多项式B 的各项系数(以‘#’结束): ");
num_2=CreCoeStr(C_2);
printf("\n请输入多项式B 的各项幂数(以‘#’结束): ");
CreExpStr(E_2);
InitPolyList(&sq_1);
InitPolyList(&sq_2);
CreatPolyList(&sq_1,C_1,E_1,num_1);
CreatPolyList(&sq_2,C_2,E_2,num_2);
printf("\n原多项式A :\n");
DispList(sq_1);
printf("\n原多项式B :\n");
DispList(sq_2);
InsertSortPoly(&sq_1);
InsertSortPoly(&sq_2);
printf("\n排列后的多项式A : \n");
DispList(sq_1);
printf("\n排列后的多项式B : \n");
DispList(sq_2);
sq_3=AddPoly(sq_1,sq_2);
printf("\n多项式相加结果: \n");
DispList(sq_3);
printf("\n");
}。

相关文档
最新文档