实现多项式的输入、输出、加法、求导、求值。
测试输入 | 期待的输出 | |
测试用例 | 5 1 2 2 5 3 8 4 9 5 12 4 1 1 3 4 5 8 -4 9 1 | A(x)+B(x)=x+x^2+3x^4+2x^5+8x^8+5x^12 A'(x)=2x+10x^4+24x^7+36x^8+60x^11 A(1)=15 |
代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct PolyNode *Polynomial;
struct PolyNode
{
int coef;
int expon;
Polynomial link;
};
void attach(int c,int e,Polynomial *prear)
{
Polynomial p;
p=(Polynomial)malloc(sizeof(struct PolyNode));
p->coef=c;
p->expon=e;
p->link=NULL;
(*prear)->link=p;
*prear=p;
}
Polynomial readpoly()
{
Polynomial p,t,rear;
p=(Polynomial)malloc(sizeof(struct PolyNode));
p->link=NULL;
rear=p;
int c,e,N;
scanf("%d",&N);
while(N--)
{
scanf("%d %d",&c,&e);
attach(c,e,&rear);
}
t=p;
p=p->link;
free(t);
return p;
}
Polynomial add(Polynomial p1,Polynomial p2)
{
Polynomial p,t,rear;
int sum;
p=(Polynomial)malloc(sizeof(struct PolyNode));
rear=p;
while(p1&&p2)
{
if(p1->expon<p2->expon)
{
attach(p1->coef,p1->expon,&rear);
p1=p1->link;
}
else if(p1->expon>p2->expon)
{
attach(p2->coef,p2->expon,&rear);
p2=p2->link;
}
else
{
sum=p1->coef+p2->coef;
if(sum)
attach(sum,p1->expon,&rear);
p1=p1->link;
p2=p2->link;
}
}
while(p1)
{
attach(p1->coef,p1->expon,&rear);
p1=p1->link;
}
while(p2)
{
attach(p2->coef,p2->expon,&rear);
p2=p2->link;
}
t=p;
p=p->link;
free(t);
return p;
}
Polynomial qiudao(Polynomial p1)
{
Polynomial p,t,rear;
int c,e;
p=(Polynomial)malloc(sizeof(struct PolyNode));
rear=p;
while(p1)
{
c=p1->coef*p1->expon;
e=--p1->expon;
++p1->expon;
if(c)
attach(c,e,&rear);
p1=p1->link;
}
t=p;
p=p->link;
free(t);
return p;
}
void printpoly(Polynomial p)
{
int flag=1;
for(; p; p = p->link)
{
if(p->coef < 0)
printf("-");
else if(!flag)
printf("+");
flag=0;
if(!(abs(p->coef) == 1 && p->expon> 0))
printf("%d", abs(p->coef));
if(p->expon> 0)
{
printf("x");
if(p->expon > 1)
printf("^%d", p->expon);
}
}
printf("\n");
}
int qiuzhi(Polynomial p1,int x)
{
int p=0;
while(p1)
{
p+=(p1->coef*pow(x,p1->expon));
p1=p1->link;
}
return p;
}
int main()
{
Polynomial p1,p2,pa,pq;
int x;
p1=readpoly();
p2=readpoly();
scanf("%d",&x);
pa=add(p1,p2);
pq=qiudao(p1);
printf("A(x)+B(x)=");
printpoly(pa);
printf("A'(x)=");
printpoly(pq);
printf("A(%d)=%d\n",x,qiuzhi(p1,x));
}