【问题标题】:explain the code line by line逐行解释代码
【发布时间】:2017-08-18 07:26:39
【问题描述】:

我在 C 中发现了这个反转字符串的代码。此代码使用递归,我无法理解 reverse() 函数。任何人都可以帮忙。

    #include <stdio.h>

    void reverse() //recursive function to reverse string.
    { 
        char c;
        scanf("%c",&c);
        if(c!='\n')
        { 
          reverse();
          printf("%c",c);
        }

    }

    void main()
    {
      printf("\nenter a string: ");
      reverse();
      getch();

    } 

【问题讨论】:

标签: c string recursion reverse


【解决方案1】:

在您的代码中, if(c!='\n') 这意味着在我们遇到新行之前,if 语句将执行。所以它将接受输入,直到遇到 \n 。 然后如果 c=\n 将执行 printf 语句,它将打印输入字符串的最后一个字符。将此递归视为 Stack 的示例。

【讨论】:

    【解决方案2】:
     #include <stdio.h>
    
    void reverse() //recursive function to reverse string.
    { 
        char c;        //declare a character
        scanf("%c",&c); //scan that is get input from user in format scanf("format specifiers",&value1,&value2,.....); 
    
        if(c!='\n')  //check if the character is blank
        { 
          reverse();   //if blank call the method reverse() again to get get input which is not blank
          printf("%c",c);  //it will print the character from last letter to first when it is not blank
        }
    
    }
    
    void main()
    {
      printf("\nenter a string: ");  //skips a line and asks user to enter a string
      reverse(); //calls method reverse()
      getch();
    
    } 
    

    【讨论】:

    • 很难解释(\n不是空白)。
    【解决方案3】:

    reverse 函数以相反的顺序打印char */字符串,例如“问题”->“noitseuq”。

    它通过逐个字符读取输入字符串(scanf 一次仅读取一个字符)并在当前字符之前的下一个字符上调用 print 来实现。

    如果您交换reverse();printf("%c",c);,您会注意到它会在当前字符 之后打印下一个字符,因此顺序与输入相同。关键是它在打印之前递归以反转字符顺序。

    【讨论】:

      猜你喜欢
      • 2016-04-04
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      相关资源
      最近更新 更多