您的位置:首页 > 编程语言 > C语言/C++

C语言的简单应用-数组实现多项式

2018-02-07 21:44 337 查看
/*这是一个基于数组实现的一个简单多项式结构
主要的缺点就是会浪费很大内存空间*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
typedef struct node
{
int num[MAX+1];//存储多项式的系数
int high;//存储多项式中次数最高项的次数
}Polymariol;
//把多项式初始化为0
void zero(Polymariol* poly)
{
for(int i=0;i<=MAX;i++)
{
poly->num[i]=0;
}
poly->high=0;
}
//两个多项式相加
void add(const Polymariol* poly1,const Polymariol* poly2,Polymariol* sum)
{
zero(sum);
sum->high = poly1->high > poly2->high ? poly1->high : poly2->high;
for(int i = sum->high;i>=0;i--)
{
sum->num[i] = poly1->num[i] + poly2->num[i];
}
}
//两个多项式相减,前者减去后者
void sub(const Polymariol* poly1,const Polymariol* poly2,Polymariol* res)
{
zero(res);
res->high = poly1->high > poly2->high ? poly1->high : poly2->high;
for(int i = res->high;i>=0;i--)
{
res->num[i] = poly1->num[i] - poly2->num[i];
}
}
//多项式乘法
void multip(const Polymariol* poly1,const Polymariol* poly2,Polymariol* res)
{
zero(res);
res->high = poly1->high + poly2->high;
if(res->high > MAX)
{
printf("Exceded array size\n");
exit(-1);
}
else
{
for(int i = poly1->high;i>=0;i--)
{
for(int j = poly2->high;j>=0;j--)
{
res->num[i+j] += poly1->num[i]*poly2->num[j];
}
}
}

}
//按照一定格式输出多项式
void show(Polymariol* p)
{
for(int x = 0;x<=p->high;x++)
{
if(x==p->high)
printf("%d*X^%d",p->num[x],x);
else
printf("%d*X^%d + ",p->num[x],x);
}
printf("\n");
}
/*
使用两个简单的多项式进行测试
p1 = 1+x1+x2
p2 = 1+x1
p1+p2 = 2 + 2x2 +x2
p2-p1 = 0 + 0 -x2
p2*p1 = 1 + 2x1 + 2x2 +x3
*/
int main(void)
{
Polymariol* p1 = (Polymariol*)malloc(sizeof(struct node));
Polymariol* p2 = (Polymariol*)malloc(sizeof(struct node));
Polymariol* res = (Polymariol*)malloc(sizeof(struct node));
zero(p1);
zero(p2);
zero(res);
p1->high = 2;
for(int a=0;a<=p1->high;a++)
{
p1->num[a]=1;
}
p2->high = 1;
for(int b=0;b<=p2->high;b++)
{
p2->num[b]=1;
}
add(p1,p2,res);
show(res);
zero(res);
sub(p2,p1,res);
show(res);
zero(res);
multip(p1,p2,res);
show(res);
//回收分配的内存空间
free(p1);
free(p2);
free(res);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C语言
相关文章推荐