首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java中多项式与常量的乘法

Java中多项式与常量的乘法
EN

Stack Overflow用户
提问于 2011-09-20 03:52:07
回答 2查看 853关注 0票数 6

我在将多项式乘以常量(双精度)时遇到了一些问题。当只有一个系数时,它起作用,但当有多个系数时,它会给出一个ArrayIndexOutOfBounds错误,并指向setCoefficient方法。有什么帮助吗?谢谢

代码语言:javascript
复制
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;
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-20 03:54:43

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

票数 4
EN

Stack Overflow用户

发布于 2011-09-20 03:54:32

我认为你应该在multiplyCon方法中替换

代码语言:javascript
复制
Poly results = new Poly();

使用

代码语言:javascript
复制
Poly results = new Poly(n);

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7476502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档