所以我试图将 2 个多项式加在一起,并且我创建了对象类型 Polynomial of ArrayBasedPoly,该对象是arraycoeff 的一个,并且度数从 0 开始。
前任: [1, 0, 3, 4] is 4x^3 + 3x^2 + 1
在我的添加类中,我试图将 2 个数组添加在一起 ->
前任: p1 = [1, 0, 3, 4], p2 = [-2, -5], Sum[] = [-1, -5, 3, 4]
但是,在 add 方法中,即使对象是数组,它也不会将 p2 识别为数组。
编辑:现在我知道我需要一个方法来找到对象 p 数组的长度,但是,即使我有一个单独的方法,它仍然找不到它?
public class ArrayBasedPoly extends Polynomial
{
private double [] poly;
public ArrayBasedPoly(double [] poly)
{
this.poly = poly;
}
public ArrayBasedPoly(double coeff, int expon)
{
super.coeff = coeff;
super.expon = expon;
}
public ArrayBasedPoly add(ArrayBasedPoly p)
{
double [] temp = new double [Math.max(p.length, poly.length)]; //<=== Here
return null; //temp
}
public String toString()
{
String s = "";
if (poly == null)
{
return super.toString(); // no poly array
}
for(int i = poly.length - 1; i >= 0; i--)
{
if (i != poly.length - 1 && poly[i] > 0) //adds + sign
{
s += " + ";
}
if (poly[i] != 0) // ignores the 0 in the array
{
if (i == 1) //if expon is 1, doesn't do the ^1
{
s += poly[i] + "x";
} else if (i > 0) { // normal
s += poly[i] + "x^" + i;
} else {
s += poly[i]; // if expon = 0, just prints out the coeff
}
}
}
return s;
}
public static void main (String [] args)
{
double [] c = {1, 0, 3, 4};
double [] c1 = {-2, -5};
Polynomial p1 = new ArrayBasedPoly (c);
System.out.println("p1(x) = " + p1);
Polynomial p2 = new ArrayBasedPoly (c1);
System.out.println("p2(x) = " + p2);
Polynomial p3 = new ArrayBasedPoly(-4, 1);
System.out.println("p3(x) = " + p3);
Polynomial p = p1.add(p2);//.add(p2);
System.out.println("p(x) = " + p);
GCT1015
呼如林
相关分类