重载+运算符将两个多项式相加
overload + operator to add 2 polynomials 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;
}
例如,案例1:最高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
}
我想你要
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;
}
您正在阅读超过较短多项式的末尾。
您似乎缺少对数组访问的边界检查。您看到奇怪值的原因是,在这种情况下,程序可能正在从未初始化的内存中读取垃圾值。但这是未定义行为,所以任何事情都有可能发生。像这样的错误最糟糕的部分是它们通常看起来工作得很好。
另外,我建议使用std::vector
来存储系数,而不是原始指针。这样更容易使用,也更不容易出错。
注:另一个小问题是,我建议在if和for语句块周围使用大括号。它使所包含的代码更加清晰,并降低了在不更新大括号的情况下意外添加额外行的风险。或者,但愿不会有人使用多行宏。但这是个人喜好的问题。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 两个文件使用彼此的功能-如何解决
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 停止cmake target_link_libraries将插件中静态库的两个对象文件链接到静态库本身
- 将fold表达式与std::一起用于两个元组
- 如何在C++中比较两个char数组
- 如何对两个 4 位数字进行乘法,将它们视为 C++ 中的多项式
- NTRUEncrypt:使用开源标准算法中的描述无法正确找到两个多项式的GCD,无法定义是否存在多边形的逆
- 重载 * 运算符以将两个多项式相乘
- 将两个多项式与向量系数进行比较C++
- 确定两个多项式相乘结果中的项数
- 重载+运算符将两个多项式相加