[英]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.