[分享]用数组来实现多项式加法.
a(x)=x+3x3+4x4+5x5b(x)=2x2+3x3+6x6;
a+b=?
代码如下..
#include "stdio.h"
#include "math.h"
#include "malloc.h"
void polyadd(int *av,int *aw,int *bv,int *bw,int *cv,int *cw);
main()
{
int av[5]={4,1,3,4,5};
int aw[5]={0,1,3,4,5};
int bv[4]={3,2,3,6};
int bw[4]={0,2,3,6};
int cv[10]={0};
int cw[10]={0};
int i;
for(i=1;i<=av[0];i++)
if(i==av[0]) printf("%d*pow(x,%d)\n",av[i],aw[i]);
else printf("%d*pow(x,%d)+",av[i],aw[i]);
for(i=1;i<=bv[0];i++)
if(i==bv[0]) printf("%d*pow(x,%d)\n",bv[i],bw[i]);
else printf("%d*pow(x,%d)+",bv[i],bw[i]);
polyadd(av,aw,bv,bw,cv,cw);
for(i=1;i<=cv[0];i++)
if(i==cv[0]) printf("%d*pow(x,%d)\n",cv[i],cw[i]);
else printf("%d*pow(x,%d)+",cv[i],cw[i]);
system("pause");
}
void polyadd(int *av,int *aw,int *bv,int *bw,int *cv,int *cw)
{
int ano=av[0],i,j,c,bno=bv[0];
int *tv=(int *)malloc(ano*sizeof(int));
int *tw=(int *)malloc(bno*sizeof(int));
for(i=1;i<=ano;i++)
{
c=aw[i];
tv[i]=av[i];
tw[i]=aw[i];
for(j=1;j<=bno;j++)
{
if(c==bw[j])
{
tv[i]=av[i]+bv[j];
bv[j]=0;
}
else if(c<bw[j]) break;
else if(c>bw[j]) continue;
}
}
c=1;
for(i=1;i<=ano;i++)
{
for(j=1;j<=bno;j++)
if(bv[j]!=0)
{
if(tw[i]<bw[j])
{
cv[c]=tv[i];
cw[c]=tw[i];
c++;
}
else
{
i--;
cv[c]=bv[j];
cw[c]=bw[j];
bv[j]=0;
c++;
}
break;
}
}
for(j=1;j<=bno;j++)
if(bv[j]!=0)
{
cv[c]=bv[j];
cw[c]=bw[j];
c++;
}
cv[0]=c-1;
free(tv);
free(tw);
}
有点多,细心研究,有收获的...
我可是花了很久来研究的哦.....