编写程序实现一元多项式的创建以及两个一元多项式相加和相乘的操作C++
时间: 2024-12-22 20:32:22 浏览: 8
在C++中,可以使用类和结构体来实现一元多项式的创建和操作。下面是一个简单的例子,展示了如何定义一个多项式类Polynomial,并实现加法和乘法运算:
```cpp
#include <iostream>
#include <vector>
// 定义多项式类
class Polynomial {
private:
std::vector<double> coefficients; // 项的系数
public:
Polynomial() {} // 构造函数,初始化为空多项式
// 添加项
void addTerm(double coefficient, double power) {
coefficients.push_back(coefficient);
coefficients.push_back(power);
}
// 从系数和指数构建多项式
explicit Polynomial(const std::vector<double>& terms) : coefficients(terms.begin(), terms.end()) {}
// 打印多项式
void print() const {
if (coefficients.empty()) return;
for (size_t i = 0; i < coefficients.size(); i += 2) {
double coef = coefficients[i];
int exp = static_cast<int>(coefficients[i + 1]);
std::cout << coef << "x^" << exp << (i == coefficients.size() - 2 ? "" : " + ");
}
std::cout << "\n";
}
// 加法运算
Polynomial operator+(const Polynomial& other) const {
Polynomial result;
size_t max_size = std::max(coefficients.size(), other.coefficients.size());
for (size_t i = 0; i < max_size; ++i) {
double coef1 = coefficients.empty() ? 0 : coefficients[i * 2];
double coef2 = other.coefficients.empty() ? 0 : other.coefficients[i * 2];
result.addTerm(coef1 + coef2, i % 2 == 1 ? coefficients[i * 2 + 1] : other.coefficients[i * 2 + 1]);
}
return result;
}
// 乘法运算
Polynomial operator*(const Polynomial& other) const {
Polynomial result;
for (const auto& term1 : coefficients) {
for (const auto& term2 : other.coefficients) {
double coef = term1 * term2;
result.addTerm(coef, term1[1] + term2[1]);
}
}
return result;
}
};
int main() {
Polynomial p1 = {1, 2, 3}; // 1 + 2x + 3x^2
Polynomial p2 = {4, 5, 6}; // 4 + 5x + 6x^2
p1.print();
p2.print();
Polynomial sum = p1 + p2;
Polynomial product = p1 * p2;
std::cout << "Sum:\n";
sum.print();
std::cout << "Product:\n";
product.print();
return 0;
}
```
在这个例子中,我们首先定义了一个`Polynomial`类,它包含一个私有向量`coefficients`存储项的系数和指数。然后实现了添加项、构造函数、打印多项式以及加法和乘法运算符。
在`main`函数中,我们创建了两个多项式实例并执行了加法和乘法操作,最后打印结果。
阅读全文