一元稀疏多项式计算器实验报告
课程名称:数据结构
实验名称: 一元稀疏多项式计算器
学 院:钱学森学院
实 验 日 期 2020年 05 月 08日
诚信承诺:我保证本实验报告中的程序和本实验报告是我自己编写,没有抄袭。
一、实验目的
- 熟悉课堂上讲过的一元多项式加法数据结构(使用链表)
- 加强C++的基本操作以及STL的使用
- 深入理解类封装,抽象的意义,并在实践中使用
二、实验环境
- 操作系统:windows10
- IDE:VSCODE
三、项目设计和实现
首先,我们需要设计数据存储的类型。这里我们使用一个struct。
struct Node
{
int cof;
int pow;
Node *next; //coefficient power
};
其次,我们使用一个链表来记录一个多项式。这里创建一个类LIST。
class List
{
public:
Node *head;
public:
~List();
void buildlst();
};
//head 为多项式的头结点
最后使用类PLOY提供多种运算符号重载
class Ploy //Polynomial
{
public:
List sequence;
//size=sequence->head->data
~Ploy()
{
// sequence.~List();
}
Ploy operator+(const Ploy &a);
Ploy operator-(const Ploy &a);
int cal(int x);
};
可以看到,POLY中提供了符号+与-的重载,这样的设计思维使得代码“零件化”,便于查错与修改。
我们详细看一下operator+的具体实现
Ploy Ploy::operator+(const Ploy &a)
{
Ploy temp;
Node *now,
*p = sequence.head->next,
*q = a.sequence.head->next; //略过头结点,因为它存储的是多项式项数
now = new Node;
temp.sequence.head = now;
now->cof = 0;
now->pow = 0;
int length = 0;
while (p != NULL && q != NULL)
{
Node *t = new Node;
now->next = t;
now = t;
t->next = NULL;
//分别处理:
//1.当前项p>q
//2.p<q
//3.p==q
if (p->pow > q->pow)
{
t->pow = p->pow;
t->cof = p->cof;
p = p->next;
}
else if (p->pow < q->pow)
{
t->pow = q->pow;
t->cof = q->cof;
q = q->next;
}
else
{
t->pow = q->pow;
t->cof = q->cof + p->cof;
p = p->next;
q = q->next;
}
length++;
// cout<<" "<<t->cof<<" ";
}
// 处理剩下的项
while (p != NULL)
{
Node *t = new Node;
now->next = t;
now = t;
t->next = NULL;
t->cof = p->cof;
t->pow = p->pow;
p = p->next;
length++;
}
while (q != NULL)
{
Node *t = new Node;
now->next = t;
now = t;
t->next = NULL;
t->cof = q->cof;
t->pow = q->pow;
q = q->next;
length++;
}
temp.sequence.head->cof = length;
return temp;
}
最后是用于测试的main函数
int main()
{
cout << "Build a Polynomial\n";
Ploy a, b;
a.sequence.buildlst();
b.sequence.buildlst();
cout << "write down the number X\n";
int x;
cin >> x;
cout << (a + b).cal(x);
cout << endl;
cout << (a - b).cal(x);
system("pause");
}
四、实验结果
可以看到输入了多项式3x^3 + 2x^2+x 和6x^4 + 2x^3,令x=2,得到结果:
A+B=642
A-B=-492
五、实验总结
本次实验独立完成了一元稀疏多项式计算器,深入理解了C++类的封装与抽象,处理了一些可能因为数据出现的错误,增强了程序的鲁棒性。但是由于C语言int大小的限制,尚不能处理更大的数据,这一点可以使用高精度计算来解决,但是已经超出了本实验的学习范围。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。