我一直在努力理解递归,它适用于斐波那契等一些示例以及如下所示的加法序列。
int AdditiveSequence(int n, int t0, int t1){
if(n == 0) return t0;
if(n == 1) return t1;
return AdditiveSequence(n - 1, t1, t0 + t1);
}
我考虑了如何应用它并尝试了这个:
static final double PERCENT = 0.005;
double Depreciation(int month, double currentValue){
if(month == 0)return currentValue;
return Depreciation(month - 1, currentValue -= currentValue * PERCENT);
}
但这似乎不是递归,更像是迭代,因为当我在 Eclipse 调试屏幕中查看时,它在 Month == 0 退出,并且迭代的 currentValue
正确返回。
对于 Factorial(n) 方法:
int Factorial(f){
if(f == 1){
return 1;
}else{
return f * Factorial(f - 1);
}
}
它似乎推迟计算直到达到基本情况,然后返回堆栈直到达到结果......
任何人都可以帮助我确定我使用上述折旧方法做了什么,以及它实际上是递归还是迭代。
最佳答案
这实际上称为尾递归,这意味着当到达递归末尾时就得到结果。这种类型的递归很容易转换为迭代代码,并且通常由编译器转换
static final double PERCENT = 0.005;
double Depreciation(int month, double currentValue){
if(month == 0)return currentValue;
return Depreciation(month - 1, currentValue -= currentValue * PERCENT);
}
在您的情况下,当前值是全程累积的,这就是它符合尾递归配置文件的原因。
关于java - 这个方法是递归还是迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957728/