我創建了一個名稱空間,並在該名稱空間內創建了一個類。該類稱爲多項式。我創建了公共成員操作符來執行多項式對象之間的算術運算。然而,當我嘗試在主要使用它們時,他們不提供正確的輸出。成員操作員不工作
我不確定如果我的錯誤是在定義或使用它們的方式。
這裏是我正在處理的文件的一部分:
header | polynomial.h
#ifndef _POLYNOMIAL_H_
#define _POLYNOMIAL_H_
//...
namespace algebra {
class polynomial {
std::vector<double> coeffStorage;
public:
//...
double operator()(double x);
polynomial operator+(polynomial p);
polynomial& operator+=(polynomial p);
polynomial operator-();
polynomial operator-(polynomial p);
polynomial& operator-=(polynomial p);
polynomial operator*(polynomial p);
polynomial& operator*=(polynomial p);
};
polynomial operator+(double c, polynomial p);
polynomial operator*(double c, polynomial p);
//...
}
#endif
cpp | polynomial.cpp
//...
//evaluates the polynomial at x
double algebra::polynomial::operator()(double x) {
double result = 0;
for (int i = 0; i < size(); i++)
result += std::pow(x, i) * getCoeff(i);
return result;
}
algebra::polynomial algebra::polynomial::operator+(algebra::polynomial p) {
algebra::polynomial result;
result.resize(degree() + p.degree() + 1);
for (int i = 0; i < result.size(); i++)
result.setCoeff(i, (getCoeff(i) + p.getCoeff(i)));
return result;
}
algebra::polynomial& algebra::polynomial::operator+=(algebra::polynomial p) {
return ((*this) = (*this) + p);
}
algebra::polynomial algebra::polynomial::operator-() {
algebra::polynomial result;
for (int i = 0; i < size(); i++)
result.setCoeff(i, -1 * getCoeff(i));
return result;
}
algebra::polynomial algebra::polynomial::operator-(algebra::polynomial p) {
return ((*this) + -p);
}
algebra::polynomial& algebra::polynomial::operator-=(algebra::polynomial p) {
return ((*this) = (*this) - p);
}
algebra::polynomial algebra::polynomial::operator*(algebra::polynomial p) {
algebra::polynomial result;
double coeffSum = 0.0;
result.resize(degree() + p.degree() + 1);
for (int i = 0; i < result.size(); i++) {
coeffSum = 0;
for (int j = 0; j <= i; j++) {
coeffSum = getCoeff(j) * p.getCoeff(i - j);
}
result.setCoeff(i, coeffSum);
}
return result;
}
algebra::polynomial& algebra::polynomial::operator*=(algebra::polynomial p) {
return ((*this) = (*this) * p);
}
algebra::polynomial algebra::operator+(double c, polynomial p) {
algebra::polynomial result = p;
result.setCoeff(0, c + p.getCoeff(0));
return result;
}
algebra::polynomial algebra::operator*(double c, polynomial p) {
algebra::polynomial result = p;
for (int i = 0; i < result.size(); i++)
result.setCoeff(i, c * p.getCoeff(i));
return result;
}
//...
多項式的係數存儲在一個向量中。每個索引屬於多項式的次數。例如,2x^2 + 3看起來像3 * x^0 + 0 * x^1 + 2 * x^2並且它在該向量上被存儲爲{3.0,0.0,2.0}。
我計劃使用的運營商主要如下:
algebra::polynomial p2;
p2.setCoeff(0, 1);
p2.setCoeff(1, 1);
algebra::polynomial p3;
p3.setCoeff(0, -1);
p3.setCoeff(1, 1);
algebra::polynomial px;
px = p2 + p3;
algebra::polynomial py;
py = p3 * p2;
但PX和PY變成空。
這將是更好,如果你可以發佈[MCVE。 –
您是否驗證過每個步驟的輸入和輸出?即setCoeff設置是否正確等? –