繁体   English   中英

使用C语言进行递归

[英]Recursion using C language

当我编译该程序时,我只会得到第一个大写字母,而其余的则不会。

输入:

ABldjfdslkjfCK

我只会得到“ A”吗?

#include <stdio.h>
#include <string.h>
FILE *fp;

int main(void)
{   
    int size; 
    char input[100]; // array size of 100 

    if (fp = fopen("message.txt","r")) // file exists
    {
        fgets(input,100,fp);// scans the sentence. 
    }
    else 
    {
    printf("file not found");// if there is no such a file. 
    }    

    size=strlen(input);  
    recursive(size,input); 

    return 0;
}

int recursive(int size, char array[])
{
    static int index = 0; // static so when the function is called, the  value is kept

    if (index < size) // start from index 0 until the size-1
    {
        if (array[index] >= 'A' && array[index] <= 'Z') // check for A to Z  (CAPITALIZE CHARACTERS only)
        {
            printf("%c\n", array[index]); // print it
        }
        else 
        {
            return recursive(size,array); // calls the function (recursion)
        }
    }
    return 0;
}

您永远不会增加index的值。 此外,如果当前字符是大写字母,则不要调用recursive函数,因此该函数仅返回。

与其将静态变量用作index ,不如将其作为recursive传递给参数; 否则,该函数是不可重入的。

您的递归函数仅在找到非大写字符时才调用自身。 当找到第一个大写字母时,将其打印并退出

您当前的函数仅打印A因为一旦找到大写字母(在您的情况下为A ),它将返回0。

还有其他问题,所以我将这样重写函数:

#include <ctype.h>  /* for isupper */

void recursive(const char* s)
{
    /* stop condition: empty string */
    if (s[0] == '\0')
        return;
    /* main body: print letter if capital */
    if (isupper(s[0]))
        printf("%c\n", s[0]);
    /* recursion: advance to the next character */
    recursive(s + 1);
}

像这样使用它: recursive(input)

递归函数具有的其他问题是index变量是静态的。 在当前版本中,这不是问题,因为除了琐碎的方式之外,您实际上并未使用它。 但是一旦尝试解决其他问题(可能导致您以更复杂的方式使用index ),使其static将带来一些问题:

  • 第一次使用后,没有正确初始化它的好方法。 这通常通过具有非递归的“包装器”函数来解决,该函数可初始化状态变量并将其传递给执行实际工作的私有递归函数(并使用值作为参数,而不使用静态实例)。 包装程序只是开始执行实际工作的功能。
  • 对该函数的递归调用将修改静态变量,该变量将修改正在进行的递归调用的“已保存”实例的状态。 如果递归是一种称为“尾递归”的类型,那么在递归调用返回后执行递归调用的调用者将不会执行任何其他工作,但是并非所有递归函数都是尾递归,那么这可能不是问题。 尽管您的示例很容易做到(不过,我仍然会尽量避免使用static变量)。

两个问题:

  1. 您错误地终止了递归。 您需要继续递归直到到达数组末尾。
  2. 您还有第二个问题,即您不递增索引,因此每个调用将始终查看第一个字符。

我看到的第一个错误是您永远不会增加索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM