复数的多项式乘法 Class

Polynomial Multiplication with Complex Numbers Class

Gist link 我的代码。 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;
}

我得到了 class 多项式,我正在尝试实现加法、减法和乘法的复数。 class 多项式通过将系数存储到数组中来工作。 [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。所以,看起来有些东西翻倍了,但我不明白为什么。

谁能找出乘法不正确的原因?

正如 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);

意味着最后一行将在 for 循环的 每次 迭代时执行,无论上述条件产生什么。即使它看起来很迂腐,我总是写大括号来避免像这样难以跟踪的错误。参见 Is it ok if I omit curly braces in Java?。如果 Jon Skeet 做到了,您也应该做到!