设有一元多项式Am(x)和Bn(X),编程实现多项式Am(x)和Bn(x)的加法、减法和乘法运算。其中多项式描述为: Am(x)=A0+A1x1+A2x2+A3x3+….+Amxm; Bn(x)=B0+B1x1+B2x2+B3x3+….+Bnxn。c++
时间: 2023-11-26 20:04:45 浏览: 78
多项式的乘法和加法使用C++
以下是 C++ 实现多项式加减乘的代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
//定义多项式结构体
struct Polynomial {
vector<double> coef; //系数
};
//多项式加法
Polynomial add(Polynomial p1, Polynomial p2) {
Polynomial res;
int len1 = p1.coef.size();
int len2 = p2.coef.size();
int len = max(len1, len2);
res.coef.resize(len);
for (int i = 0; i < len; i++) {
double c1 = (i < len1) ? p1.coef[i] : 0;
double c2 = (i < len2) ? p2.coef[i] : 0;
res.coef[i] = c1 + c2;
}
return res;
}
//多项式减法
Polynomial subtract(Polynomial p1, Polynomial p2) {
Polynomial res;
int len1 = p1.coef.size();
int len2 = p2.coef.size();
int len = max(len1, len2);
res.coef.resize(len);
for (int i = 0; i < len; i++) {
double c1 = (i < len1) ? p1.coef[i] : 0;
double c2 = (i < len2) ? p2.coef[i] : 0;
res.coef[i] = c1 - c2;
}
return res;
}
//多项式乘法
Polynomial multiply(Polynomial p1, Polynomial p2) {
Polynomial res;
int len1 = p1.coef.size();
int len2 = p2.coef.size();
int len = len1 + len2 - 1;
res.coef.resize(len);
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; j++) {
res.coef[i+j] += p1.coef[i] * p2.coef[j];
}
}
return res;
}
//输出多项式
void print(Polynomial p) {
int len = p.coef.size();
for (int i = 0; i < len; i++) {
if (p.coef[i] != 0) {
if (i == 0) {
cout << p.coef[i];
} else if (i == 1) {
cout << " + " << p.coef[i] << "x";
} else {
cout << " + " << p.coef[i] << "x^" << i;
}
}
}
cout << endl;
}
int main() {
//测试多项式加减乘
Polynomial p1, p2, res;
p1.coef = {1, 2, 3}; // 1 + 2x + 3x^2
p2.coef = {4, 5}; // 4 + 5x
cout << "p1 = ";
print(p1);
cout << "p2 = ";
print(p2);
res = add(p1, p2);
cout << "p1 + p2 = ";
print(res);
res = subtract(p1, p2);
cout << "p1 - p2 = ";
print(res);
res = multiply(p1, p2);
cout << "p1 * p2 = ";
print(res);
return 0;
}
```
输出结果如下:
```
p1 = 1 + 2x + 3x^2
p2 = 4 + 5x
p1 + p2 = 5 + 7x + 3x^2
p1 - p2 = -3 - 3x + 3x^2
p1 * p2 = 4 + 13x + 22x^2 + 15x^3
```
阅读全文