数据结构:设计ADT-多项式

Polynomial.h

操作:求值、合并多项式

#pragma once

struct Term
{
	int power = 0;
	int k = 0;
};

class Polynomial
{
public:
	Polynomial();
	~Polynomial();

	int getLength();
	int evaluate(int x);
	Polynomial& operator+= (const Polynomial& other);

private:
	int length = 0;
	Term* terms;
};

Polynomial.cpp

#include "Polynomial.h"
#include <iostream>
using namespace std;
Polynomial::Polynomial()
{
	cout << "input from high power to low power" << endl << "how many terms:";
	cin >> length;
	
	terms = new Term[length];
	for (int i = 0; i != length; i++) {
		cout << "k:";
		cin >> terms[i].k;
		cout << "power:";
		cin >> terms[i].power;
	}
	cout << "creation complete" << endl;

}

Polynomial::~Polynomial()
{
	delete[] terms;
}

int Polynomial::getLength()
{
	return length;
}

int Polynomial::evaluate(int x)
{
	int result = 0;
	for (int i = 0; i != length; i++) {
		result += (terms[i].k) * pow(x, terms[i].power);
	}
	return result;
}

Polynomial& Polynomial::operator+=(const Polynomial& other)
{
	Term* result = new Term[length + other.length];
	int i = 0, j = 0, k = 0;
	while (i != length and j != other.length) {
		if (terms[i].power > other.terms[j].power)
			result[k++] = terms[i++];
		else if (terms[i].power < other.terms[j].power)
			result[k++] = other.terms[j++];
		else if (terms[i].power == other.terms[j].power) {
			result[k].k = terms[i].k + other.terms[j].k;
			result[k].power = terms[i].power;
			k++;
			i++;
			j++;
		}
	}
	while (i != length) result[k++] = terms[i++];
	while (j != other.length) result[k++] = other.terms[j++];
	delete[] terms;
	terms = result;
	length += other.length;
	return *this;
}

Main function

#include <iostream>
#include "Polynomial.h"
using namespace std;



int main()
{
    Polynomial poly1, poly2;
    poly1 += poly2;
    cout << poly1.evaluate(2);
}

运行结果:

input from high power to low power
how many terms:2
k:2
power:3
k:1
power:1
creation complete
input from high power to low power
how many terms:3
k:1
power:2
k:1
power:1
k:1
power:0
creation complete
25

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值