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

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

#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

{ 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);

相关文档
最新文档