C++ forloop中的一个递归是如何工作的?

C++ forloop中的一个递归是如何工作的?,c++,recursion,C++,Recursion,我不理解这个例子。我理解递归函数的原理,但在这个例子中,我不能理解forloop中的递归。 有人能给我解释一下这个例子吗 #include <iostream> using namespace std; void f(int n) { cout << n; for (int i=3; i<n; i=i+1) f(n-1); cout << n; } int main() { f(5); return 0; } #包括

我不理解这个例子。我理解递归函数的原理,但在这个例子中,我不能理解forloop中的递归。 有人能给我解释一下这个例子吗

#include <iostream>

using namespace std;

void f(int n) 
{
 cout << n;

 for (int i=3; i<n; i=i+1)
    f(n-1); 

 cout << n;
}

int main()
{
  f(5);
 return 0; 
}
#包括
使用名称空间std;
空f(整数n)
{

cout它的工作原理与递归在其他任何地方的工作原理相同。该函数调用自身。由于它在一个循环中,它可能会多次这样做

是什么让你感到困惑

我建议用一张纸一步一步地写下输出应该是什么。始终遵循逻辑。

f(5)将调用f(4)两次,即I=3和4

f(4)将调用f(3)一次,即i=3


f(3)不会再调用f,因为
3很抱歉,这是用java编写的,不是用C编写的,但我已经把它打印出来了。
在我看来,这可能是最容易理解的递归算法。
5的阶乘为120,以供参考

    1. run through the code
    2. write down the value of variables at each point 
    3. check the output with the correct answer
一旦理解了这个简单的递归算法,请再次运行复杂的示例,看看它是否更有意义

Java示例:

公共类主{
公共静态void main(字符串[]args){
//TODO自动生成的方法存根
系统输出打印LN(事实(5));
}
公共静态整数事实(整数n){
if(n<1){
返回1;
}
否则{
返回n*事实(n-1);
}
}
} 

希望这有帮助!

执行它并读取它打印的内容如何?是的,我执行了它,但不理解答案。我知道它打印的内容,但不理解为什么。它打印:543344335。尝试使用调试器并查看每个步骤的输出。还可以尝试在
cout
中添加一些额外的内容,如
cout非常感谢你!它帮助了我!什么时候我进入forloop,然后我必须返回带有f(4)的函数,然后它在forloop中打印4,然后再次返回到f(3),然后在forloop中打印3(3我在这个例子上花了1个小时,无法理解它。@Georgi函数打印了两次
n
。这就是为什么会得到两个3。请注意,3是最终条件,因为我被设置为3,并且必须f(5) 5 // on entry f(4) // because i is 3, n is 5 4 // on entry f(3) // because i is 3, n is 4 3 // on entry // no further call because i is 3, n is 3 3 // on return // no further call because i is 4, n is 4 4 // on return f(4) // because i is 4, n is 5 4 // on entry f(3) // because i is 3, n is 4 3 // on entry // no further call because i is 3, n is 3 3 // on return // no further call because i is 4, n is 4 4 // on return // no further call because i is 5, n is 5 5 // on return
5433443345
    1. run through the code
    2. write down the value of variables at each point 
    3. check the output with the correct answer
public class Main {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(fact(5));
}

public static int fact(int n){
    if(n < 1){
        return 1;
    }
    else{
        return n*fact(n-1);
    }
}
}