eeeeeeeee

作者在 2006-10-18 19:58:00 发布以下内容

/*1. 用户从键盘输入若干数值对,输入形式为:系数(double),幂(非负整数)
,当输入的幂为负数时表示输入结束。输入无大小、顺序的要求。

2. 根据用户输入的内容创建两个多项式,完成下列功能:

    1)输出所创建的两个多项式

    2)完成多项式的加法、减法

    3)完成多项式的乘法

    4)输出加法、乘法、减法运算后的结果。*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
 struct Link
{
 double coef;
 unsigned int expn;
 struct Link *next;
};
//创建链表
struct Link *create(int i)
{
 struct Link *p1,*p2,*head;
 double c;
 int e;
 p1=(struct Link*)malloc(sizeof(struct Link));
 head=p1;
 printf("建立第%d个二项式:\n",i);
 
 scanf("%lf,%d",&c,&e);
 while(e>=0)
 {
 p1->coef=c;
 p1->expn=e;
 p2=p1;
 p1=(struct Link*)malloc(sizeof(struct Link));
 p2->next=p1;
 scanf("%lf,%d",&c,&e);
 }
 p2->next=NULL;
    return head;
}
//输出多项式
void print(struct Link *p)
{
 if(p)
 {printf("%lfX(%d)",p->coef,p->expn);
 p=p->next;}
 while(p)
 {
 printf("+%lfX(%d)",p->coef,p->expn);
 p=p->next;
 }
}
//比较元素
int comp(int a,int b)
{ if(a>b) return 1;
 else if(a=b) return 0;
 else return -1;
}

//多项式加法
struct Link *add(struct Link *pa,struct Link *pb)
{
 struct Link *ha,*hb,*qa,*qb,*p,*q,*head;
 double sum;
 ha=pa;hb=pb;
 
 while(ha&&hb)
 {
  switch(comp(ha->expn,hb->expn))
 {
  case -1:
    
    ha=ha->next;break;
  case 0:
    sum=ha->coef+hb->coef;
    if(sum!=0.0)
    {
     ha->coef=sum;
     ha=ha->next;
     p=hb->next;
    free(hb);
    hb=p;
    }
    else
    {
     p=ha->next;free(ha);ha=p;
     q=hb->next;free(hb);hb=q; 
     }break; 
   
  case 1:
      p=ha;ha=hb;ha=p;
      q=hb->next;free(hb);hb=q;
   break;
 
  }
 }
if(pb) ha=hb;
free(pb);
 return head;
}
 
//多项式减法
//多项式乘法
//主函数
void main()
{
 struct Link *head1=create(1);
 struct Link *head2=create(2);
 struct Link *h1;
 printf("多项式一为:\n\tS1=");
 print(head1);
 printf("\n");
 printf("多项式二为:\n\tS2=");
 print(head2);
 printf("\n");
 h1=add(head1,head2);
 printf("多项式一+多项式二为:\n\tS1+S2=");
 print(h1);
}

作业草稿 | 阅读 1257 次
文章评论,共0条
游客请输入验证码