c++ - 重载 + 运算符以添加 2 个多项式 C++

标签 c++

<分区>

我正在编写将 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: 最高 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

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    
}

最佳答案

我觉得你想要

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

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

关于c++ - 重载 + 运算符以添加 2 个多项式 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15182448/

相关文章:

c++ - C++ 的模块概念

c++ - 字符串分析

c++ - 在 Windows 7 操作系统上创建/删除新用户帐户

c++ - 在 C++ 中,std::string::push_back() 的摊销复杂度是 O(1) 吗?

c++ - 加载后图像尺寸增加

C++ 数组索引

java - 通过一个Database类访问数据库,紧耦合?破坏建议零售价?

c++ - 确定kubernetes pod重新启动的原因

c++ - 创建模板函数的每个实例时,模板函数 typedef 说明符是否会被正确内联?

c++ - 令人费解的非尾随参数包行为