
大家好。我目前的大學任務是使用遞回來表示霍納的方法。在此任務之前,我們必須使用回圈來完成,這很容易。但我不知道如何使用只有 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 個
uj5u.com熱心網友回復:
正如我在評論中建議的那樣,繼續從多邊形陣列中切下頭部并將切碎的版本傳遞給遞回呼叫,就像這樣(這可能會有所幫助):
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
}
}
uj5u.com熱心網友回復:
為了使用雙引數方法,您可以呼叫包含實際遞回邏輯的方法,提供0(給定陣列的第一個索引)作為第三個引數。
請注意,遞回的基本情況是當我們到達最后一個元素a n時,即當 indexn等于 時a.length - 1。
否則,呼叫應該由遞回 case處理,包含符合霍納規則的邏輯。
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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/528990.html
標籤:爪哇算法递归数学
上一篇:如何遍歷結構化的正則運算式搜索?
