0

我正在尝试使用重载 * 运算符编写乘以 2 个多项式

这是重载 * func

Polynomial Polynomial::operator * (const Polynomial &right)
{
    Polynomial temp;
    temp.setPolynomial(right.maxExp + maxExp + 1);
    for (int i = 0; i < maxExp; i++)
    {
        for (int j = 0; j < right.maxExp; j++)
            temp.poly[1][i+j] += poly[0][i] * right.poly[0][j];
    }
    return temp;
}

数组结果,其中第一行是系数,第二行存储指数。

The first (original) polynomial is: (degree = 4, F = x^2)
0 0 1 0 0
0 0 2 0 0
The second polynomial is: (degree = 4, F = x^2)
0 0 1 0 0
0 0 2 0 0
The result polynomial is: // the location of the result is right (x^4)
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0

多项式类

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; // get the maxExp (highest exponent)
    int getCoefficient(int,int) const; // get a specific exponential value

    // overloading operators
    void operator=(const Polynomial &); // assignment
    Polynomial operator+(const Polynomial &); // addition
    Polynomial operator-(const Polynomial &); // substraction
    Polynomial operator*(const Polynomial &);
}

问题:我的代码产生该值有什么问题?谢谢!

4

1 回答 1

1

这样,您将使用多个系数更新结果指数;

 temp.poly[1][i+j] += poly[0][i] * right.poly[0][j];

我认为代码应该是

for (int j = 0; j < right.maxExp; j++)
{
    temp.poly[0][i+j] += poly[0][i] * right.poly[0][j];
    if (temp.poly[0][i+j] != 0)
        temp.poly[1][i+j] = i+j;
}

我还认为在您的代码中存储指数是冗余信息,因为数组本身的位置反映了指数

于 2013-03-03T08:02:13.427 回答