在Java中将多项式乘以常量

时间:2011-09-19 19:52:07

标签: java math

我在将多项式乘以常数(double)时遇到了一些问题。它只有一个系数,但当多于一个时,它会产生一个ArrayIndexOutOfBounds错误,并指向setCoefficient方法。有帮助吗?感谢

public class Poly {
    private float[] coefficients;

    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 Poly multiplyCon (double c){
        int n = getDegree();
        Poly results = new Poly();
        // can work when multiplying only 1 coefficient
        for (int i =0; i <= coefficients.length-1; i++){
                // errors ArrayIndexOutOfBounds for setCoefficient
            results.setCoefficient(i, (float)(coefficients[i] * c)); 
        }
        return results;
    }
}

2 个答案:

答案 0 :(得分:4)

我相信你应该用multiplyCon方法替换

Poly results = new Poly();

Poly results = new Poly(n);

Poly默认构造函数创建只有一个系数的数组,这解释了为什么乘以单系数多项式的原因。

答案 1 :(得分:4)

Poly results = new Poly();替换为Poly results = new Poly(n);