我的代码的Gist链接。 The problem I'm having uses the class Polynomial, method multiply, lines 136-172.
以下是方法:
public Polynomial multiply(Polynomial right){
int size = right.length + length -1;
int i;
int r;
Complex productCoeff;
Complex coeffP = new Complex();
Complex coeffQ = new Complex();
Complex currentValue;
Polynomial temp = new Polynomial(size);
for (i = 0; i < length; i++)
{
for (r = 0; r < right.length; r++) {
coeffP = (retrieveAt(i));
coeffQ = (right.retrieveAt(r));
productCoeff = coeffP.multiplyComplex(coeffQ);
if (temp.retrieveAt(i+r) == null)
currentValue = productCoeff;
else
currentValue = (temp.retrieveAt(i+r));
currentValue = currentValue.addComplex(productCoeff);
temp.replaceAt(i+r, currentValue);
}
}
return temp;
}
我被赋予了Polynomial类,我正在尝试为加法,减法和乘法实现复数。类多项式通过将系数存储到数组中来工作。 [x ^ 0,x ^ 1,x ^ 2,x ^ 3 ...]我得到加法和减法来处理复数,但是我无法使乘法正常工作。
我的思维过程乘以复数:对于在第一个数组中循环的每个项目,我想循环遍历第二个数组中的所有项目并相乘。在每个乘法系列之后,我想将此值存储到临时数组中。如果临时数组在该位置具有值,我想将乘积值添加到临时数组中该位置存储的值。如果临时数组中该位置没有值,我可以简单地替换它。
该方法适用于常规多项式,但使用复数时,我得到的答案不正确。例如:
((1+2i)+(3+4i)x) ((2+7i)+(4+3i)x)
应该等于(-12+11i) + (-24+40i)x + (25i)x^2
但是当我运行该程序时,我的答案是(-24+22i) + (-26+51i)x + (50i)x^2
。所以,看起来有些东西正在翻倍,但我无法弄清楚原因。
任何人都可以找出乘法不正确的原因吗?
答案 0 :(得分:1)
正如saka1029已经提到的:你的代码缩进与其逻辑结构不匹配。你的if-else构造
if (temp.retrieveAt(i+r) == null)
currentValue = productCoeff;
else
currentValue = (temp.retrieveAt(i+r));
currentValue = currentValue.addComplex(productCoeff);
实际上会被解释为
if (temp.retrieveAt(i+r) == null) {
currentValue = productCoeff;
} else {
currentValue = (temp.retrieveAt(i+r));
}
currentValue = currentValue.addComplex(productCoeff);
意味着无论上述条件产生什么,最后一行都将在{{1>}循环的每次迭代上执行。即使它看起来很迂腐,我总是写括号以避免难以跟踪这样的错误。见Is it ok if I omit curly braces in Java?。如果 Jon Skeet 做到了,你也应该这样做!