建立一个多项式类(CPoly),多项式类的数据成员包括最高幂次,各项系数,操作包括加法、减法、乘法、显示和输入。
时间: 2024-05-03 21:21:50 浏览: 16
以下是一个简单的CPoly类的实现:
```cpp
class CPoly {
private:
int degree; // 最高幂次
double* coef; // 各项系数
public:
// 构造函数
CPoly(int deg): degree(deg) {
coef = new double[degree+1];
for (int i = 0; i <= degree; i++) {
coef[i] = 0;
}
}
// 拷贝构造函数
CPoly(const CPoly& poly) {
degree = poly.degree;
coef = new double[degree+1];
for (int i = 0; i <= degree; i++) {
coef[i] = poly.coef[i];
}
}
// 析构函数
~CPoly() {
delete[] coef;
}
// 输入多项式
void input() {
cout << "请输入多项式的各项系数:\n";
for (int i = degree; i >= 0; i--) {
cin >> coef[i];
}
}
// 显示多项式
void display() const {
cout << "多项式:";
for (int i = degree; i >= 0; i--) {
if (coef[i] != 0) {
if (i == degree) {
cout << coef[i] << "x^" << i;
} else {
cout << " + " << coef[i] << "x^" << i;
}
}
}
cout << endl;
}
// 加法运算
CPoly operator+(const CPoly& poly) const {
int maxDegree = max(degree, poly.degree);
CPoly result(maxDegree);
for (int i = 0; i <= maxDegree; i++) {
result.coef[i] = coef[i] + poly.coef[i];
}
return result;
}
// 减法运算
CPoly operator-(const CPoly& poly) const {
int maxDegree = max(degree, poly.degree);
CPoly result(maxDegree);
for (int i = 0; i <= maxDegree; i++) {
result.coef[i] = coef[i] - poly.coef[i];
}
return result;
}
// 乘法运算
CPoly operator*(const CPoly& poly) const {
int maxDegree = degree + poly.degree;
CPoly result(maxDegree);
for (int i = 0; i <= degree; i++) {
for (int j = 0; j <= poly.degree; j++) {
result.coef[i+j] += coef[i] * poly.coef[j];
}
}
return result;
}
};
```
使用示例:
```cpp
int main() {
CPoly poly1(3), poly2(2);
poly1.input();
poly2.input();
CPoly sum = poly1 + poly2;
CPoly diff = poly1 - poly2;
CPoly prod = poly1 * poly2;
poly1.display();
poly2.display();
sum.display();
diff.display();
prod.display();
return 0;
}
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)