我正在寫函數將2個多項式加在一起,其中2個多項式具有相同數量的最高度(所有項不需要輸入)的情況都可以正常工作,其中的兩個多邊形有不同程度的不工作,該功能在某種程度上存儲一些大的值作爲係數超載+運算符添加2個多項式C++
這是函數
// overload +
Polynomial Polynomial::operator+(const Polynomial &right)
{
// get the highest exponent value for result
int highestExp = 0;
if (maxExp < right.maxExp)
highestExp = right.maxExp;
else if (maxExp >= right.maxExp)
highestExp = maxExp;
Polynomial res;
res.setPolynomial(highestExp);
for (int coeff=0; coeff < highestExp; coeff++)
res.poly[0][coeff] = poly[0][coeff] + right.poly[0][coeff];
return res;
}
例如, 案例1:最高EXPS相等
The first (original) polynomial is:
- 4x^0 + x^1 + 4x^3 - 3x^4
The second polynomial is:
- x^0 - x^3
The result polynomial is:
- 5x^0 + x^1 + 3x^3 - 3x^4
個
案例2:最高的指數是不相等的
The first (original) polynomial is:
- 4x^0 + x^1 + 4x^3 - 3x^4 (highest exp = 4)
The second polynomial is:
- x^0 - x^3 (highest exp = 5)
The result polynomial is:
- 5x^0 + x^1 + 3x^3 - 3x^4 - 33686019x^5 (highest exp = 5)
請幫助!
更新:多項式類
class Polynomial
{
private:
int **poly;
int maxExp;
void createPolynomialArray(int);
public:
Polynomial();
Polynomial(int); // constructor
Polynomial(const Polynomial &); // copy constructor
~Polynomial(); // destructor
// setter
void setCoefficient(int,int);
void setPolynomial(int);
// getters
int getTerm() const;
int getCoefficient(int,int) const;
// overloading operators
void operator=(const Polynomial &); // assignment
Polynomial operator+(const Polynomial &); // addition
}
爲了加快這個問題,找到多項式類的實際定義可能會*奇蹟*。請將其包含在您的問題文章中。謝謝。 – WhozCraig 2013-03-03 04:33:57
您可能正在讀取低階多項式中係數緩衝區的末尾。在循環中,一旦「coeff」大於較小多項式的階數,就應該停止從較小多項式的元素中讀取數據。 – Mankarse 2013-03-03 04:35:53