我似乎无法弄清楚我做错了什么。我试图返回数组D,但我得到的确切错误信息是:
Pa4.java:74: incompatible types
found : double[]
required: double
return D;
^
我遇到问题的方法如下。
static double diff(double[] C){
double D[];
D = new double[(C.length-1)];
for(int i = C.length; i > 0; i -= 1){
int deg = 1;
D[i] = deg * C[i];
deg++;
}
for(int i = 0; i < C.length; i++){
D[i] = C[i];
}
return D;
}
我的完整代码如下。它非常不完整,所以希望问题出现在我给出的第一个代码块中:
import java.util.Scanner;
import java.lang.Math;
class Pa4{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int degree;
double C[];
double resolution = 10^(-2);
double threshhold = 10^(-3);
double tolerance = 10^(-7);
System.out.print("Enter the degree: ");
degree = sc.nextInt();
C = new double[degree];
System.out.print("Enter "+(degree+1)+" coefficients: ");
for(int i = 0; i < degree+1; i++){ // 1st number = last to enter
C[i] = sc.nextInt(); //stores coefficiant values in reverse order in an array
}
System.out.print("Enter the left and right endpoints: ");
int a = sc.nextInt();
int b = sc.nextInt();
double x = findRoot(C, a, b, tolerance);
double saf = poly(C, x);
double sdf = diff(C);
double asdf = poly(D, x);
}
static double poly(double[] C, double x){
double sum = 0;
for(int i = 0; i <= C.length; i =- i){
int deg = 1;
deg++;
double hold = Math.pow(C[i], deg);
hold = hold*x;
sum = hold+sum;
}
return sum;
}
static double diff(double[] C){
double D[];
D = new double[(C.length-1)];
for(int i = C.length; i > 0; i -= 1){
int deg = 1;
D[i] = deg * C[i];
deg++;
}
for(int i = 0; i < C.length; i++){
D[i] = C[i];
}
return D;
}
static double findRoot(double[] C, double a, double b, double tolerance){
double x = 0;
double width = b-a;
while(width > tolerance){
x = (a + b)/2.0;
if((a*a-2.0)*(x*x-2.0) < 0){
b = x;
}else{
a = x;
}
width = b-a;
}
return x;
//use precondition (?)
}
}
答案 0 :(得分:2)
您的diff
方法返回单个double
,但您尝试返回double
数组。将回复类型更改为double[]
,并将通话更改为double[] sdf = diff(C);
BTW,您的diff方法还有其他问题:
D数组的长度为C.length - 1,但是您尝试将整个C数组分配给D.您将获得ArrayIndexOutOfBoundsException
该方法的大多数代码都没有意义,因为第二个循环将C的元素分配给D,因此方法的整个主体可以替换为return C
。