|  | 
 
 发表于 2024-10-2 16:30:32
|
显示全部楼层 
| 本帖最后由 jackz007 于 2024-10-2 20:30 编辑 
 1、一个函数调用自己,或者,多个函数彼此相互调用,形成闭环的,都是递归(A->B->C->D->A),其中,前者比较常见;
 
 2、递归函数必须设置结束条件,并相应设置继续递归和结束递归两个分支;
 
 3、递归有深度限制,递归过深会导致调用栈耗尽而出错;
 
 4、递归与循环功能相似,相比之下,递归的效率显著低于循环,递归更适用于循环次数不可预知的情形;
 
 考察下面的代码,以便加深理解:
 
 复制代码#include <stdio.h>
void foo(char s[] , int n)
{
        if(s[n]) {
                printf("%c" , s[n])                        ; // 【进入过程】正序打印字符串
                foo(s , n + 1)                             ;
                printf("%c" , s[n])                        ; // 【退出过程】逆序打印字符串
        } else {
                printf("\n【递归终点】\n")                 ;
        }
}
int main(void)
{
        char a[] = "I'm a chinese, I love my motherland !" ;
        foo(a , 0)                                         ;
        printf("\n")                                       ;
}
编译运行实况:
 
 复制代码D:\[exercise]\C>g++ -o x x.c
D:\[exercise]\C>x
I'm a chinese, I love my motherland !
【递归终点】
! dnalrehtom ym evol I ,esenihc a m'I
D:\[exercise]\C>
 用循环替换递归的代码版本是这样的:
 
 复制代码#include <stdio.h>
int main(void)
{
        char s[] = "I'm a chinese, I love my motherland !" ;
        int n                                              ;
        for(n = 0 ; s[n] ; n ++) printf("%c" , s[n])       ;
        n --                                               ;
        printf("\n【递归终点】\n")                         ;
        for(; n >= 0 ; n --) printf("%c" , s[n])           ;
        printf("\n")                                       ;
}
 | 
 |