我正在尝试创建一个程序,可以添加存储在数组中的两个多项式。多项式的每个项(系数和指数)作为一个索引存储在一个数组中(我有一个术语类来执行此操作)。当我调用我的add方法时,它并不总是组合具有相同指数的系数。
如果指数相似,我的最后一个条件会增加2个系数。在已经分配一个Term之后,我如何创建一个遍历我的多项式的循环?也许有更有效的方法来解决这个问题。
public Polynomial add(Polynomial p1, Polynomial p2)
{
int i = 0;
int j = 0;
int newin = 0; //index or location of new terms being stored for Polynomial p3
Polynomial p3 = new Polynomial();
while (i<p1.TermLength || j<p2.TermLength)
{
if (i==p1.TermLength)
{
p3.poly[newin].setCoeff(p2.poly[j].getCoeff());
p3.poly[newin].setExpo(p2.poly[j].getExpo());
j++; // j is increased whenever a term from Poly2 has been utilized
}
else if (j==p2.TermLength)
{
p3.poly[newin].setCoeff(p1.poly[i].getCoeff());
p3.poly[newin].setExpo(p1.poly[i].getExpo());
i++; // i is increased by 1 whenever a term from Poly1 has been utilized
}
else if (p1.poly[i].getExpo()>p2.poly[j].getExpo())
{
p3.poly[newin].setCoeff(p1.poly[i].getCoeff());
p3.poly[newin].setExpo(p1.poly[i].getExpo());
i++;
}
else if (p1.poly[i].getExpo()<p2.poly[j].getExpo())
{
p3.poly[newin].setCoeff(p2.poly[j].getCoeff());
p3.poly[newin].setExpo(p2.poly[j].getExpo());
j++;
}
else if (p1.poly[i].getExpo() == p2.poly[j].getExpo())
{
p3.poly[newin].setExpo(p1.poly[i].getExpo());
p3.poly[newin].setCoeff(p1.poly[i].getCoeff() + p2.poly[j].getCoeff());
i++;
j++;
}
newin++;
}
p3.TermLength = p3.poly.length;
return p3;
}