zoukankan      html  css  js  c++  java
  • 函数递归及总复习

    函数递归:

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

    最简单的递归:
    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);
            }

  • 相关阅读:
    mac重启nginx时报nginx.pid不存在的解决办法
    js 正则表达式
    js 闭包
    js yarn
    js npm
    vue3 vite
    node 错误处理
    node fs
    linux包管理工具使用和区别(转)
    MySQL数据库学习----理论基础
  • 原文地址:https://www.cnblogs.com/123lucy/p/5553381.html
Copyright © 2011-2022 走看看