java - 多项式数组表示无法正常工作

标签 java

我正在尝试创建一个多项式类,其中多项式由系数/指数对数组​​表示。我创建了 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

最佳答案

你的代码读起来很痛苦,你应该格式化它。空间很便宜,不要吝啬。不要只将所有功能都放在左边距;缩进它们,以便它们的位置和范围显而易见。

count变量是多余的。只需使用 poly.length反而。

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

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

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

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

关于java - 多项式数组表示无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19708580/

相关文章:

java - 我在使用 FileReader 将 txt 文件写入数组 (Java) 时遇到问题,我做错了什么?

java - JPA:@ManyToOne,1 表中不必要的重复条目

java - JCalendar问题(二月份)

Java:通过 TCP 传输文件

java - 使用 Date.parse(dateString) 给定日期的毫秒数是错误的

java - 如何知道所需的核心数和内存数?

java - 用于将应用程序拆分为前端/后端的意见/ header (不是用户/管理员,而是 ui/逻辑)

java - Alog 转换为 Java

Java 方法返回错误值

java - 全屏 DialogFragment 与 StatusBar 重叠