2012-10-06 99 views
1

我很困惑递归在这个例子中如何工作。如果输入'ABC \ n',则输出CBA。如果有人能够通过这个过程,我将不胜感激。C++递归堆栈

  1. 在main(),ReverseLine()被调用
  2. 本地automtic myInput取入 'ABC \ N'

  3. 然后检查myInput关于 '\ n' 和EOF,这就是我开始越来越困惑

我认为它说,A!= '\ n' 和阿!= EOF所以ReverseLine()再次调用,但然后呢???

如何递归的工作,我只是想了解的过程

THANKS

using namespace std; 

    void ReverseLine(){ 
     int myInput; 

     myInput = cin.get(); 

     if (myInput != '\n' && myInput != EOF) 
     ReverseLine(); 

     if (myInput != EOF) 
     cout.put(myInput); 
    } 

    int main(){ 

     ReverseLine(); 
     return 0; 

    } 
+1

您已标记此问题C,但它是一个C++程序。 –

+3

您是否尝试使用调试器(例如Linux上的'gdb')以及单步执行('gdb'的''step'命令),并且回溯调试执行的程序?递归的解释可能很困难,而且这很大程度上取决于您的文化和科学背景。 –

+0

你确定它有效吗? –

回答

4

当您调用ReverseLine时,它会读取一个字符。如果字符不是换行符或EOF,它会再次调用自身(递归)读取下一个字符,直到遇到新行,此时它会打印刚刚读取的字符,然后返回到ReverseLine,它会打印它读取的字符并直到它返回到ReverseLine的初始调用,打印第一个读取的字符,然后退出。

4

也许扩展它会帮助你明白吗?

void ReverseLine() { 
    int myInput = 'a' 

    if (myInput != '\n' && myInput != EOF) { 
     int myInput = 'b' 

     if (myInput != '\n' && myInput != EOF) { 
      int myInput = 'c' 

      if (myInput != '\n' && myInput != EOF) { 
       int myInput = '\n' 
       if (myInput != '\n' && myInput != EOF) 
        ReverseLine(); // doesn't get called 
       cout.put(myInput); 
      } 
      if (myInput != EOF) 
       cout.put(myInput); 
     } 

     if (myInput != EOF) 
     cout.put(myInput); 
    } 

    if (myInput != EOF) 
    cout.put(myInput); 
} 
2

正如Basile所说,递归可能很难理解。这个例子依赖于局部变量的概念。它将进入递归层的末尾,然后从最深的递归调用开始打印本地变量myInput

假设您输入“123”。每个缩进都是ReverseInput()的新的局部范围。

myInput = 1 
ReverseLine() 
    myInput = 2 
    ReverseLine() 
    myInput = 3 
    ReverseLine() 
     myInput = \n 
    prints 3 
    prints 2 
prints 1 

这是一种常见的伎俩,以相反的方式做事。

1

这真的很简单。 ReverseLine函数在返回之前打印其输出。这是事件发生的顺序,如果* ABC \ n

1. First call to ReverseLine. 
1.a **A** is typed. 
1.b myInput is not equal to **\n or EOF**, so 
    2. Second call to ReverseLine 
    2.a **B** is typed. 
    2.b myInput is not equal to **\n** or **EOF**, so 
     3. Third call to ReverseLine 
     3.a **C** is typed. 
     3.b myInput is not equal to **\n** or **EOF**, so 
     4. Fourth call to ReverseLine 
     4.a **\n** is typed. 
     4.b myInput is equal to **\n**, so 
     4.c ReverseLine is **not** called 
     4.d myInput is **not** equal to **EOF**, so 
     4.e myInput (**\n**) is printed 
     4.f Fourth call to ReverseLine returns 
     3.c myInput is **not** equal to **EOF**, so 
     3.d myInput (**C**) is printed 
     3.e Third call to ReverseLine returns 
    2.c myInput is **not** equal to **EOF**, so 
    2.d myInput (**B**) is printed 
    2.e Second call to ReverseLine returns 
1.c myInput is **not** equal to **EOF**, so 
1.d myInput (**A**) is printed 
1.e First call to ReverseLine returns 

键入然后程序结束。