gpt4 book ai didi

java - 将两个多项式存储为 java 中的链表

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:47:31 25 4
gpt4 key购买 nike

我有一个单项式结构,它将三个变量的系数和指数作为一个数字。我的单项式类如下所示:

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

我的输入看起来像这样
多项式1:
10
1个
2个
3个
11
4个
5个
6个
多项式2:
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
这不是所需的输出。计算未正确执行。我知道我的循环体有问题,但我不知道是什么。我想知道出了什么问题以及如何纠正它。

最佳答案

您的算法完全错误。只需用纸和铅笔看看会发生什么:您对每个单项式进行 n 次处理,这不是多项式加法所做的。

正确的方法是构建一个方法,将一个单项式添加到现有的多项式上,并迭代添加的多项式。但这还不是全部,您计算单个系数以在单个操作中比较 3 个整数值的技巧仅在所有单个系数都在 0-9 范围内时才有效...

关于java - 将两个多项式存储为 java 中的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44278138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com