0

我正在尝试创建一个多项式类,其中多项式由一组系数/指数对表示。我创建了 add 方法来添加两个多项式,但我的值却被重复了。

public class Poly{


private static class Pair{

int coeff;
int exponent;

private Pair(){

this.coeff=coeff;
this.exponent=exponent;
 }

private Pair(int coef, int exp){

exponent = exp;
coeff = coef;
 }

}

int count=2;
private Pair[] poly; //creates an Array of coefficient/exponent pairs

public Poly(){

poly = new Pair[count];
for(int i=0;i<count;i++){
poly[i] = new Pair(0,0);
 }

}


public Poly(int coeff1, int exp){

int i=0;
poly = new Pair[count];
for(i=0; i<count; i++){
poly[i]= new Pair(coeff1, exp);
}

count++;
}

private Poly (int exp) {

poly = new Pair[exp+1];
   poly[0].exponent = exp;
   poly[0].coeff=1;

}


**public Poly add(Poly q){**
Poly result = new Poly();
int j=0;

while(j<poly.length){

    for(int i=0; i<q.poly.length; i++){

        if(poly[j].exponent==q.poly[i].exponent){
        result.poly[j].coeff= poly[j].coeff+q.poly[i].coeff;
        result.poly[j].exponent =poly[j].exponent;
        }
        else if(poly[j].exponent!=q.poly[i].exponent && i<q.poly.length){
        result.poly[j].coeff= q.poly[i].coeff;
        result.poly[j].exponent =q.poly[i].exponent;
        }

        else if(poly[j].exponent!=q.poly[i].exponent && i==q.poly.length-1){
        result.poly[j].coeff= poly[j].coeff;
        result.poly[j].exponent =poly[j].exponent;
        }

    }
    j++;
}
return result;
}





public String toString(){

String str = "";

for(int i=0; i<poly.length; i++){

    if(poly[i].coeff==0){
        str+="";
    }

    else{
    str+="+" +poly[i].coeff +"x^"+poly[i].exponent;
}
}
return str;
}


}

我试图得到一个值作为两个多项式 (5x^9) 和 (3x^8) 的总和以返回 5x^9+3x^8

public static void main(String[] args) {

Poly a =new Poly(5,9);
Poly b =new Poly(3,8);

    System.out.println(a);
    System.out.println(b);
    System.out.println("the sum of the poly is: " +ab);

}

输出是

a=+5x^9+5x^9
b=+3x^8+3x^8
the sum of the poly is: +3x^8+3x^8
4

2 回答 2

1

你的代码读起来很痛苦,你应该格式化它。空间很便宜,不要吝啬它们。不要只将所有功能都粘在左边距上;缩进它们,这样它们的位置和范围就很明显了。

count变量是多余的。改用就好poly.length了。

目前,Poly.sub(x)应该只是实现为return add(minus(x));. 它效率低下但简单且显然正确。

您如何决定设置Poly[]数组大小?你count用来设置它们,这可能是错误的。也许您应该java.util.ArrayList<Pair>改用,并且只add()对他们使用。我不明白你怎么没有得到数组越界异常。

mult()没有正确地乘以多项式。你如何合并具有相同指数的乘积项?

创建一个函数,然后使用andPoly Poly.pairMult(Pair)重新实现。mult()pairMult()add

于 2013-10-31T14:33:34.133 回答
0
Poly a = new Poly( 5, 9 );
System.out.println( a );

+5x^9+5x^9

我假设您只想+5x^9输出?

你有一个循环toString()将迭代count次数,count初始化为 2。

于 2013-10-31T14:12:58.090 回答