本文介绍了在Java中将多项式乘以常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在将多项式乘以常数(双精度)时遇到一些问题.当只有一个系数但有一个以上系数时,它起作用,它给出ArrayIndexOutOfBounds错误并指向setCoefficient方法.有什么帮助吗?谢谢
I'm having some problems with multiplying a Polynomial by a constant (double). It works when theres only one coefficient but when more then one is there, it gives a ArrayIndexOutOfBounds error and points to the setCoefficient method. Any help? Thanks
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;
}
}
推荐答案
将Poly results = new Poly();
替换为Poly results = new Poly(n);
.
这篇关于在Java中将多项式乘以常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!