现在的位置: 首页 > 06 函数 > 正文

递归实例

2011年12月07日 06 函数 ⁄ 共 611字 ⁄ 字号 暂无评论

递归(英语:Recursion),又译为递回,在数学与计算机科学中,是指在函数的定义中使用函数自身的方法。

【语言例子】

从前有座山,山里有座庙,庙里有个老和尚,正在给小和尚讲故事呢!故事是什么呢?“从前有座山,山里有座庙,庙里有个老和尚,正在给小和尚讲故事呢!故事是什么呢?‘从前有座山,山里有座庙,庙里有个老和尚,正在给小和尚讲故事呢!故事是什么呢?……’”

写出下面程序的运行结果:

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
 
int f(int x)
{
    if(x==0||x==1)return 3;
    return x*x-f(x-2);
}
void main()
{
    printf("%d\n",f(3));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
 
void fun(int m,int n)
{
    if(m>=n)
        printf("%d",m);
    else
        fun(m+1,n);
    printf("%d",m);
}
 
int main()
{
    fun(1,2);
    return 0;
}

输入 1 3 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<stdio.h>
 
void f(int a, int b, int c)
{
    printf("%d%d%d/", a, b, c);
    if(a == 3 && b == 2 && c == 1)
        return;
    if(b < c)
        f(a, c, b);
    else if(a < b) {
        if(a < c)
            f(c, a, b);
        else
            f(b, c, a);
    }
}
 
int main()
{
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);
    f(a, b, c);
    printf("\n");
    return 0;
}

抱歉!评论已关闭.