函数递归及总复习

函数递归:

含义:函数自己调用自己的过程;

最简单的递归:
public static void Test1(int a)
{
//if条件很重要,就像循环中的循环条件,没有的话就永远出不来了
if (a >= 10000)
{
return;
}
a++; //这个地方也很重要,就像状态改变;
Console.WriteLine(a);
Test1(a);
}

运行机制:
一层一层往里进,到了进不了的地方,再一层一层退出来

打印菲波那切数列:

        static void Main(string[] args)
        {           
            int a = 0, b = 1;
            Console.WriteLine(a);
            Console.WriteLine(b);
            lx(a, b);

            Console.ReadKey();

        }
        public static void lx(int a, int b)
        {
            int c = a + b;
            if (c >= 1000)
            {
                return;
            }
            Console.WriteLine(c);
            lx(b, c);
        }

BOSS题
写一个函数,输入一个数,返回斐波那契数列中这个数的位置的数;
0 1 1 2 3 5 8 13 21 34 55 89

        static void Main(string[] args)
        {
            Console.Write("请输入一个正整数:");
            int n= Convert.ToInt32(Console.ReadLine());

            Console.WriteLine(boss(n));

            Console.ReadKey();
        }

        public static int boss(int n)
        {
            int i = 1;
            int j = 2;
            if (n < 1)
            {
                return 0;
            }
            else if (n == 1 || n == 2)
            {
                return 1;
            }
            return boss(n - i) + boss(n - j);
        }

原文地址:https://www.cnblogs.com/123lucy/p/5553381.html