【发布时间】:2017-05-31 07:17:28
【问题描述】:
我有一个单项式结构,它接受一个系数和三个变量的指数作为一个数字。我的单项式类看起来像这样:
public class Monomial {
private Float coeff;
private Integer exp;
private Integer x,y,z;
public Monomial() {
this.coeff=null;
this.x=this.y=this.z=null;
this.exp=null;
}
public Monomial(Float coeff, Integer x, Integer y, Integer z) {
this.coeff = coeff;
this.x = x;
this.y = y;
this.z = z;
this.exp = (100*x)+(10*y)+z;
}
public Monomial(Integer exp) {
this.exp = exp;
this.x=(exp-(exp%100))/100;
this.z = exp%10;
this.y = ((exp-z)/10)%10;
}
public Monomial(Float coeff, Integer exp) {
this.coeff = coeff;
this.exp = exp;
this.x=(exp-(exp%100))/100;
this.z = exp%10;
this.y = ((exp-z)/10)%10;
}
}
我的多项式类存储为单项式链表。
我想添加 2 个多项式。这是我的加法函数
public Polynomial addition(Polynomial a, Polynomial b) {
LinkedList<Monomial> Main = new LinkedList<>();
LinkedList<Monomial> temp1 = a.getPolynomial();
LinkedList<Monomial> temp2 = b.getPolynomial();
for(int i = 0;i<temp1.size();i++){
for(int j = 0;j<temp2.size();j++){
Integer c1= temp1.get(i).getExp();Integer c2 = temp2.get(j).getExp();
if(c1.equals(c2)){
Float k1 = temp1.get(i).getCoeff();Float k2 = temp2.get(j).getCoeff();
Main.add(new Monomial( k1+k2,temp2.get(j).getExp()));
//temp1.remove(i);temp2.remove(j);
}
else if(!c1.equals(c2)){
Main.add(new Monomial(temp1.get(i).getCoeff(),temp1.get(i).getExp()));
//temp1.remove(i);
Main.add(new Monomial(temp2.get(j).getCoeff(),temp2.get(j).getExp()));
//temp2.remove(j);
}
}
}
Polynomial ret = new Evaluator(Main);
return ret;
}
我的输入看起来像这样
Polynomial1:
10
1
2
3
11
4
5
6
Polynomial2:
12
1
2
3
13
4
5
6
多项式 1 可以解释为 10x(y^2)(z^3) 等等。
我得到的输出是:
22.0 1 2 3
10.0 1 2 3
13.0 4 5 6
这不是所需的输出。计算未正确执行。我知道我的循环体有问题,但我不知道它是什么。
我想知道出了什么问题以及如何纠正它。
【问题讨论】:
-
你应该逐步调试你的代码并检查为什么循环
for(int i = 0;i<temp1.size();i++){只对第一个条目执行。 -
一个问题很可能是
if(c1==c2)。这不是比较对象的值,它是在检查两个对象是否是同一个对象——可能不是你的意思。尝试使用c1.equals(c2)进行值比较。
标签: java algorithm linked-list