大学生做c课程设计:一元多项式数据结构,排错排不出来了求指教
大家好我是一名大二的学生正在做数据结构的课程设计,题目是一元多项式计算,c语言实现
要求:输入系数和指数,输出多项式,之后进行加减乘法运算
本人今天敲了一下午(纯手写纯自己编)
之后在笔记本的vs2012旗舰版上运行时,界面出现很多000还有很大的数之类的一直刷屏
我想了好久也不知道错在哪里,求各位牛人帮忙解决一下
代码:
#include<stdio.h>
#include<stdlib.h>
struct node
{int exp;
double coef;
node *next;};
void init_poly(node **head){
node *p;
p=(struct node*)malloc(sizeof(node));
p->coef=-1;
p->exp=-1;
p->next=p;
*head=p;
return;
}
void prt_poly(node *head){
node *p;
if(head->next==head)
{ printf("空表!");
return;}
p=head->next;
printf("%fx^%d",p->coef,p->exp);
p=p->next;
while(p!=head){
if(p->coef>0)
printf("+%fx^%d",p->coef,p->exp);
else printf("%fx^%d",p->coef,p->exp);
p-p->next;
}
printf("\n");
return;
}
void creat(node *head){
node *k,*p;
int e;
double c;
k=head;
printf("请按降幂输入一元多项式,输入格式:系数〈空格〉指数〈空格〉系数〈空格〉指数。。。指数输入-1结束!\n");
scanf("%f%d",&c,&e);
while(e!=-1){
p=(struct node*)malloc(sizeof(node));
p->exp=e;
p->coef=c;
p->next=head;
k->next=p;
k=p;
scanf("%f%d",&c,&e);
}
return;
}
void del_poly(node *head){
node *p,*q;
p=head->next;
while(p!=head){
q=p;
p=p->next;
delete q;
}
p->next=head;
}
struct node* jiafa(node *head1,node *head2){
node *k,*q,*m,*n;
node *head;
int e;double c;
m=head1->next;
n=head2->next;
init_poly(&head);k=head;
while((m->exp!=-1)||(n->exp!=-1)){
if (m->exp==n->exp)
{c=m->coef+n->coef;
e=n->exp+m->exp;
m=m->next;
n=n->next;
}
else if (m->exp>n->exp)
{c=m->coef;e=m->exp;
m=m->next;}
else {c=n->coef;e=n->coef;
n=n->next;}
if(c!=0)
{q=(struct node*)malloc(sizeof(node));
q->coef=c;q->exp=e;
q->next=head;
k->next=q;
k=q;
}
}
del_poly(head1);
del_poly(head2);
return(head);
}
struct node*chengfa(node*head1,node*head2){
node *head,*head0;
node *k,*q,*m,*n;
m=head1->next;
init_poly(&head0);
init_poly(&head);
while(m->exp!=-1){
n=head2->next;
k=head0;
while(n->exp!=-1){
q=(struct node*)malloc(sizeof(node));
q->exp=m->exp+n->exp;
q->coef=m->coef*n->coef;
q->next=head0;
k->next=q;
k=q;
n=n->next;
}
head=jiafa(head,head0);
m=m->next;
}
del_poly(head1);
del_poly(head2);
return(head);
}
void main(){
node *head1,*head2,*k;
int flag=1,c;
while(flag==1){
printf("1.创建一个多项式 2.加法运算 3.减法运算 4.乘法运算 5.释放多项式 6.退出\n");
printf("请输入要进行的选项:");scanf("%d",&c);
switch(c){
case 1:
init_poly(&head1);creat(head1);
printf("您输入的表达式为:");prt_poly(head1);break;
case 2:printf("请再输入一个表达式:");
init_poly(&head2);creat(head2);
printf("您输入的表达式为:");prt_poly(head2);
head1=jiafa(head1,head2);
printf("二者相加后的表达式为:");prt_poly(head1);break;
case 3:printf("请再输入一个表达式:");
init_poly(&head2);creat(head2);
printf("您输入的表达式为:");prt_poly(head2);
k=head2->next;
while(k!=head2){
k->coef=(-1)*k->coef;
k=k->next;
}
head1=jiafa(head1,head2);
printf("二者相加减的表达式为:");prt_poly(head1);break;
case 4:printf("请再输入一个表达式:");
init_poly(&head2);creat(head2);
printf("您输入的表达式为:");prt_poly(head2);
head1=chengfa(head1,head2);
printf("二者相加乘的表达式为:");prt_poly(head1);break;
case 5:del_poly(head1);
printf("一元多项式已经释放!请重新选择功能。");break;
default:flag=0;break;
}
}
}