[c语言] 输入多项式,求导数并输出。

#include<stdio.h>
#include<malloc.h>
typedef struct node {
    int coef;
    int expn;
    struct node* next;
}PLOYList;

//创建多项式链表
PLOYList* create() {
    PLOYList* head;
    PLOYList* input;
    PLOYList* tail;
    int x, y, n;
    head = NULL;
    tail = head;
    input = (PLOYList*)malloc(sizeof(PLOYList));
    //n为多项式的项数
    printf("please input the number of items.\n");
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d %d", &x, &y);
        input->coef = x;
        input->expn = y;
        input->next = NULL;
        if (head == NULL) {
            head = input;
            tail = input;
        }
        else {
            tail->next = input;
            tail = input;
        }
    }
    free(input);
    return head;
}


//多项式求导
PLOYList* der(PLOYList* head)
{
    PLOYList* p;
    p = head->next;
    while (p != NULL)
    {
        p->coef = p->coef * p->expn;
        p->expn = p->expn--;
        p = p->next;
    }
    return head;
}


//输出多项式
void print(PLOYList* f)
{
    PLOYList* p;
    p = f;
    //第一项没有加号,先输出
    printf("%d*", p->coef);
    printf("x^%d", p->expn);
    p = p->next;
    while (p != NULL)
    {
        /* 打印运算符号和系数 */
        if (p->coef >= 0) {
            printf("+");
            printf("%d*", p->coef);
        }//正系数加加号
        else if (p->coef < 0) //负系数直接输出
            printf("%d", p->coef);
        /* 打印指数 */
        printf("x^%d", p->expn);
        p = p->next;
    }
    printf("\n");
}


int main()
{
    PLOYList* f;
    f = create();
    printf("f(x)="); print(f);
    printf("f'(x)="); print(der(f));
    printf("\n");
    return 0;
}

写了好久也不知道是哪里的问题,求大佬解答(⑉・̆-・̆⑉)

查看全部
qq_41754782
打火鸡
2020/12/04 19:52
  • c语言
  • 点赞
  • 收藏
  • 回答
    私信

0个回复