大家好。我目前的大学作业是使用递归来表示Horner 方法。在此任务之前,我们必须使用循环来完成它,这很简单。但我不知道如何使用只有 2 个无法更改的参数的递归来做到这一点。
public static double evalHornerRec(double[] a, double x)
这是我必须使用的功能
private static int horner(int a[], int x, int n){
int h;
if(n>0)
h=horner(a, x, n-1);
else
return a[n];
return h*x+a[n];
}
我发现了类似的东西,但它有 3 个参数而不是 2 个
正如我在评论中建议的那样,继续将多边形数组的头切掉,并将切碎的版本传递给递归调用,就像这样(this提供了一个示例):
public class Main {
static int horner(int a[], int x) {
switch (a.length) {
case 1: return a[0];
default: return a[0] + x * horner(Arrays.copyOfRange(a, 1, a.length), x);
}
}
public static void main(String[] args) {
// 2x^3 - 6x^2 + 2x - 1 for x = 3 => 5
int[] poly = {-1, 2, -6, 2};
System.out.println(horner(poly, 3)); // 5
}
}
为了使用 two-args 方法,您可以调用包含实际递归逻辑的方法,并提供
0
(给定数组的第一个索引)作为第三个参数。
注意,递归的基本情况是当我们到达最后一个元素an时,即当索引
n
等于a.length - 1
时。
否则,调用应该由递归情况处理,包含符合霍纳规则的逻辑。
public static double evalHornerRec(double[] a, double x) {
return horner(a, x, 0);
}
private static double horner(double a[], double x, int n) {
if (n == a.length - 1) return a[n];
return a[n] + x * horner(a, x, n + 1);
}