java 一元稀疏多项式简单计算器,一元稀疏多项式计算器实验报告

一元稀疏多项式计算器实验报告

课程名称:数据结构

实验名称: 一元稀疏多项式计算器

学 院:钱学森学院

实 验 日 期 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

//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<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");

}

四、实验结果

1460000022589341

可以看到输入了多项式3x^3 + 2x^2+x 和6x^4 + 2x^3,令x=2,得到结果:

A+B=642

A-B=-492

五、实验总结

本次实验独立完成了一元稀疏多项式计算器,深入理解了C++类的封装与抽象,处理了一些可能因为数据出现的错误,增强了程序的鲁棒性。但是由于C语言int大小的限制,尚不能处理更大的数据,这一点可以使用高精度计算来解决,但是已经超出了本实验的学习范围。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值