0

我正在编写将两个多项式相加的函数,两个多项式具有相同数量的最高次数(不需要输入所有项)的情况可以正常工作,但是两个多项式具有不同次数的情况不起作用,函数以某种方式存储一些大值作为系数

这是功能

// 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:最高的 exp 相等

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

case2:最高指数不相等

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    
}
4

2 回答 2

1

我想你想要

Polynomial Polynomial::operator+(const Polynomial &right)
{
    Polynomial res;
    if(maxExp < right.maxExp)
    {
        res.setPolynomial(right.maxExp);
        int coeff = 0;
        for (; coeff < maxExp; coeff++)
                res.poly[0][coeff] = poly[0][coeff] + right.poly[0][coeff];
        for (; coeff < right.maxExp; coeff++)
                res.poly[0][coeff] = right.poly[0][coeff];
    }
    else
    {
        res.setPolynomial(maxExp);
        int coeff = 0;
        for (; coeff < right.maxExp; coeff++)
                res.poly[0][coeff] = poly[0][coeff] + right.poly[0][coeff];
        for (; coeff < maxExp; coeff++)
                res.poly[0][coeff] = poly[0][coeff];
    }
    return res;
}

您正在阅读较短多项式的末尾。

于 2013-03-03T04:44:53.823 回答
0

您似乎缺少对数组访问的边界检查。您看到奇怪值的原因是,在这种情况下,程序可能正在从未初始化的内存中读取垃圾值。但这是未定义的行为,所以实际上任何事情都可能发生。像这样的错误最糟糕的部分是它们通常看起来工作正常。

另外,我建议使用std::vector来存储系数而不是原始指针。它更容易使用并且更不容易出错。

PS 另一个挑剔的是,我建议在 if 和 for 块周围使用大括号。它可以更清楚地准确包含哪些代码,并降低在不更新大括号的情况下意外添加额外行的风险。或者天堂禁止,有人使用多行宏。但这是一个品味问题。

于 2013-03-03T04:42:21.317 回答