c++ 建立一个多项式类(CPoly),多项式类的数据成员包括最高幂次,各项系数,操作包括加法、减法、乘法、显示和输入。
时间: 2024-06-04 22:10:50 浏览: 11
class CPoly {
private:
int degree; // 最高幂次
double* coeff; // 各项系数
public:
CPoly(int deg = 0); // 构造函数
CPoly(const CPoly& poly); // 拷贝构造函数
~CPoly(); // 析构函数
CPoly operator+(const CPoly& poly) const; // 加法运算符重载
CPoly operator-(const CPoly& poly) const; // 减法运算符重载
CPoly operator*(const CPoly& poly) const; // 乘法运算符重载
void display() const; // 显示多项式
void input(); // 输入多项式
};
CPoly::CPoly(int deg) {
degree = deg;
coeff = new double[degree + 1];
for (int i = 0; i <= degree; i++) {
coeff[i] = 0;
}
}
CPoly::CPoly(const CPoly& poly) {
degree = poly.degree;
coeff = new double[degree + 1];
for (int i = 0; i <= degree; i++) {
coeff[i] = poly.coeff[i];
}
}
CPoly::~CPoly() {
delete[] coeff;
}
CPoly CPoly::operator+(const CPoly& poly) const {
int maxDegree = (degree > poly.degree) ? degree : poly.degree;
CPoly result(maxDegree);
for (int i = 0; i <= maxDegree; i++) {
result.coeff[i] = coeff[i] + poly.coeff[i];
}
return result;
}
CPoly CPoly::operator-(const CPoly& poly) const {
int maxDegree = (degree > poly.degree) ? degree : poly.degree;
CPoly result(maxDegree);
for (int i = 0; i <= maxDegree; i++) {
result.coeff[i] = coeff[i] - poly.coeff[i];
}
return result;
}
CPoly 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.coeff[i + j] += coeff[i] * poly.coeff[j];
}
}
return result;
}
void CPoly::display() const {
for (int i = degree; i >= 0; i--) {
if (i != degree && coeff[i] >= 0) {
cout << "+";
}
cout << coeff[i] << "x^" << i;
}
cout << endl;
}
void CPoly::input() {
cout << "请输入最高幂次:";
cin >> degree;
coeff = new double[degree + 1];
cout << "请输入各项系数:";
for (int i = degree; i >= 0; i--) {
cin >> coeff[i];
}
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)