[英]How does Linear Recursion work?
我編寫了一個Java程序,使用線性遞歸在數組中添加元素。 獲得的輸出與預期不符。 誰能指出這個程序有什么問題嗎?
public class TestSum {
public int count = 0;
public int sum(int[] a){
count++;
if(a.length == count){
return a[count -1];
}
return sum(a) + a[count -1] ;
}
public static void main(String[] args) {
int[] a = {1,2,3};
int val = new TestSum().sum(a);
System.out.println(val);
}
}
我期望輸出為6但獲得的是9 。 怎么了?
奇怪的是,如果我改變加法順序,即return a[count -1] + sum(a);
然后給出輸出為6 。
通常,不重入的遞歸程序(即依賴外部狀態)是可疑的。 在您的特殊情況下, count
將在sum
調用之間發生變化,從而使行為難以跟蹤,最終導致您觀察到錯誤。
您應該將索引與數組一起傳遞以使其工作:
// The actual implementation passes the starting index
private static int sum(int[] a, int start){
if(a.length == start){
return 0;
}
return sum(a, start+1) + a[start];
}
// Make sure the method can be called with an array argument alone
public static int sum(int[] a) {
return sum(a, 0);
}
與增加方法外部計數的實現不同,此實現可以在多個線程上並發調用而不會中斷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.