所以我的问题是让这个程序结合类似的术语,我尝试了3种不同的方法来解决这个问题并且无法解决这个问题。我可以按照正确的顺序对数组进行排序,但不能将它组合起来。
public static Node multiply(Node poly1, Node poly2) {
Node polynomial1 = poly1;
Node polynomial2 = poly2;
Node mult = poly2;
Node temp3 = null;
float cmb = 0;
int cmbExp = 0;
// the sum of the polynomials
Node temp = null;
float coeffProd;
int expSum;
if(poly1 == null)
return "Enter a Different Polynomial";
if(poly2 == null)
return "Enter a Different Polynomial";
// while loop if either polynomial runs out of terms. This avoids nullpointerexception
while (polynomial1 != null) {
while(polynomial2 != null){
coeffProd = polynomial1.term.coeff * polynomial2.term.coeff;
expSum = polynomial1.term.degree + polynomial2.term.degree;
temp = new Node(coeffProd, expSum, temp);
polynomial2 = polynomial2.next;
}
polynomial1 = polynomial1.next;
polynomial2 = mult;
}
// my attempt at combining
Node temp2 = temp.next;
while(temp != null){
while(temp2 != null){
if(temp.term.degree == temp2.term.degree){
cmb = temp.term.coeff + temp2.term.coeff;
cmbExp = temp.term.degree;
}
temp2 = temp2.next;
temp3 = new Node(cmb,cmbExp,temp3);
}
temp = temp.next;
}
// Reverses the Polynomial into the correct sequence
Node flip = temp;
Node ans = null;
while (flip != null)
{
if (flip.term.coeff == 0)
{
flip = flip.next;
continue;
}
else
{
ans = new Node(flip.term.coeff, flip.term.degree, ans);
flip = flip.next;
}
}
if (ans == null)
return null;
else
{
return ans;
}
}
结果: 32.0x ^ 9 + 16.0x ^ 8 + -12.0x ^ 6 + 36.0x ^ 5 + -16.0x ^ 7 + -8.0x ^ 6 + 6.0x ^ 4 + -18.0x ^ 3 + 16.0x ^ 5 + 8.0 x ^ 4 + -6.0x ^ 2 + 18.0x + 24.0x ^ 4 + 12.0x ^ 3 + -9.0x + 27.0
我需要结合这些条款。
答案 0 :(得分:0)
如果遍历度数,可以简化组合。这也保证了组合多项式是按顺序创建的。
以下工作代码演示了一种可能的组合方式,并创建了所需的结果。
public Node multiply(Node poly1, Node poly2) {
if (poly1 == null || poly2 == null)
return null;
Node polynomial1 = poly1;
Node polynomial2 = poly2;
Node allTerms = null;
float coeffProd;
int expSum;
int maxDegree = 0;
while (polynomial1 != null) {
while (polynomial2 != null) {
coeffProd = polynomial1.term.coeff * polynomial2.term.coeff;
expSum = polynomial1.term.degree + polynomial2.term.degree;
allTerms = new Node(coeffProd, expSum, allTerms);
if (expSum > maxDegree)
maxDegree = expSum;
polynomial2 = polynomial2.next;
}
polynomial1 = polynomial1.next;
polynomial2 = poly2;
}
/* Combine terms */
Node combinedNode = null;
for (int i = 0; i<= maxDegree; i++) {
Node temp = allTerms;
float fSum = 0;
while (temp != null) {
if (temp.term.degree == i)
fSum+=temp.term.coeff;
temp = temp.next;
}
if (fSum != 0)
combinedNode = new Node(fSum, i, combinedNode);
}
return combinedNode;
}