列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少

2023-05-16

列数的规则如下: 1、1、2、3、5、8、13、21、34…… 求第30位数是多少

分析:从第二个数开始,每位等于前两个数相加


递归:

 public static void Do()
        {
            int endnum = Foo(30);
            Console.WriteLine(endnum.ToString());
        }


        public static int Foo(int index)
        {
            if (index <= 0)
            {
                return 0;
            }
            else if (index == 1 || index == 2)
            {
                return 1;
            }
            return Foo(index - 1) + Foo(index - 2);
        }

循环:

public static void Do2()
        {
            Console.WriteLine(Foo2(30).ToString());
        }

        public static int Foo2(int positionIndex)
        {
            if (positionIndex <= 0)
            {
                throw new Exception("处理不了!");
            }
            else if (positionIndex <= 2)
            {
                return 1;
            }

            int index1 = 1;
            int index2 = 1;
            int index = 0;
            for (int i = 2; i < positionIndex; i++)
            {
                index = index1 + index2;
                index1 = index2;
                index2 = index;
            }
            return index;
        }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少 的相关文章

随机推荐