具备一元多项式加、减、乘的运算功能

1个回答

  • 这个程序是我们课设题目,只实现了一元多项式的相加,然后对(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);

    }