public class Algo{
public static void main(String[] args){
System.out.println(bar(4));
}
static int bar(int n){
if(n==0 || n==1){
return 1;
}else{
return n-bar(n-1);
}
}
}
所以我认为上面的代码是这样做的:
n=4: 4-(4-1) = 4-3 = 1
n=3: 1-(3-1) = 1-2 = -1
n=2: -1-(2-1) = -1-1 = -2
n=1: Now we get into the if-statement, this basically means that bar(1) = 1, so in the end we have that -2-1 = -3
但是当我编译并运行它时,我得到了不同的输出,我不明白为什么..?
Output: 2
我尝试了另一种与这个算法非常相似的算法(只是带有乘法符号,也就是 faculty)并且在这次试运行中它成功了。但它似乎不适用于该算法。
最佳答案
这是它的计算方式:
bar(4) =
4 - bar(3) =
4 - (3 - bar(2)) =
4 - (3 - (2 - bar(1))) =
4 - (3 - (2 - 1)))
4 - 3 + 2 - 1 =
2
关于java - 短算法(递归)的试运行问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45091993/