2つの多項式を足し合わせる関数を書いています。2つの多項式の最高次数が同じである場合(すべての項を入力する必要はありません)は正常に機能しますが、2つの多項式の次数が異なる場合は機能しません。関数はどういうわけか係数としていくつかの大きな値を格納します
これが機能です
// 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;
}
たとえば、case1:最高の経験値は等しい
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
}