gpt4 book ai didi

java - Java 多项式类

转载 作者:行者123 更新时间:2023-12-02 06:16:33 26 4
gpt4 key购买 nike

我正在尝试为多项式类创建两种方法,但遇到了麻烦。第一个方法 checkZeros 应该检查多项式的系数中是否有任何前导零。如果存在前导零,该方法应调整系数数组的大小。第二种方法应该找到多项式的导数,但我不断收到 ArrayIndexOutOfBounds 错误。

它们在这里:

public class Poly {

private float[] coefficients;
public static void main (String[] args){
float[] fa = {3, 2, 4};
Poly test = new Poly(fa);

}

public Poly() {
coefficients = new float[1];
coefficients[0] = 0;
}

public Poly(int degree) {
coefficients = new float[degree+1];
for (int i = 0; i <= degree; i++)
coefficients[i] = 0;
}


public Poly(float[] a) {
coefficients = new float[a.length];
for (int i = 0; i < a.length; i++)
coefficients[i] = a[i];
}

public int getDegree() {
return coefficients.length-1;
}

public float getCoefficient(int i) {
return coefficients[i];
}

public void setCoefficient(int i, float value) {
coefficients[i] = value;
}

public Poly add(Poly p) {
int n = getDegree();
int m = p.getDegree();
Poly result = new Poly(Poly.max(n, m));
int i;

for (i = 0; i <= Poly.min(n, m); i++)
result.setCoefficient(i, coefficients[i] + p.getCoefficient(i));
if (i <= n) {
//we have to copy the remaining coefficients from this object
for ( ; i <= n; i++)
result.setCoefficient(i, coefficients[i]);
} else {
// we have to copy the remaining coefficients from p
for ( ; i <= m; i++)
result.setCoefficient(i, p.getCoefficient(i));
}
return result;
}

public void displayPoly () {
for (int i=0; i < coefficients.length; i++)
System.out.print(" "+coefficients[i]);
System.out.println();
}

private static int max (int n, int m) {
if (n > m)
return n;
return m;
}

private static int min (int n, int m) {
if (n > m)
return m;
return n;
}


public void checkForZeros(){
int newDegree = getDegree();
int length = coefficients.length;
double testArray[] = coefficients;

for (int i = length - 1; i >0; i--) {
if (coefficients[i] != 0) {
testArray[i] = coefficients[i];

}
}

for (int j = 0; j < testArray.length; j++){
coefficients[j] = testArray[j];
}
}


public Poly differentiate(){
int n = getDegree();
int newPolyDegree = n - 1;
Poly newResult = new Poly();

if (n == 0){
newResult.setCoefficient(0, 0);
}
for (int i =0; i<= n; i++){
newResult.setCoefficient(i, coefficients[i+1] * (i+1));
}
return newResult;
}
}

最佳答案

我怀疑问题就在这里

   for (int i =0; i<= n; i++){
newResult.setCoefficient(i, coefficients[i+1] * (i+1));
}

由于n = getDegree();,我们假设多项式为一阶(例如 1+x)。那么我猜 n=1,系数的长度为 2。但是您将检查系数[2](因为您有 i+1),这是超出范围的。我猜你想要

   for (i=0; i<=newPolyDegree; i++){
newResult.setCoefficient(i, coefficients[i] * (i+1));
}

或者其他什么...很难用您提供的代码量来判断。

关于java - Java 多项式类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21397295/

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