使用术语数组的多项式加法

时间:2013-11-24 11:14:47

标签: arrays

我正在尝试创建一个程序,可以添加存储在数组中的两个多项式。多项式的每个项(系数和指数)作为一个索引存储在一个数组中(我有一个术语类来执行此操作)。 当我调用我的add方法时,它并不总是组合具有相同指数的系数。

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;
}

0 个答案:

没有答案