Unity中使用C#递归输出数组1,2,3,5,8,...该数组的生成规律是每一个数字是前两个数字的和

一、实现思路:第一个数大于等于0,第二个数大于等于第一个数,最后指定一个需要输出的最后一个数字(该数字用作最后输出的界限)

①实现脚本如下:

/***
*	Title:"XXX" 项目
*		主题:XXX
*	Description:
*		功能:XXX
*	Date:2018
*	Version:0.1版本
*	Author:Coffee
*	Modify Recoder:
*/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SimpleUIFrame
{
    public class Test_recursion : MonoBehaviour
    {
        List<int> numbers;

        void Start()
	{
            numbers = new List<int>();
            GetTwoNumber(0,1,20);
           
            foreach (var b in numbers)
            {
                Debug.Log(b);
            }
	}



        /// <summary>
        /// 递归获取第三个数是前两数之和的数组
        /// </summary>
        /// <param name="firstValue">第一个开始数字</param>
        /// <param name="SecodValue">第二个开始数字</param>
        /// <param name="lastValue">最后一个输出的数字</param>
        /// <returns></returns>
        private void GetTwoNumber(int firstValue, int SecodValue,int lastValue)
        {
            int ThirdValue=0;
           
            if (firstValue >= 0)
            {
                if (firstValue<=SecodValue)
                {
                    ThirdValue = firstValue + SecodValue;
                    firstValue = SecodValue;
                    SecodValue = ThirdValue;

                    if (SecodValue < lastValue)
                    {
                        numbers.Add(ThirdValue);
                        GetTwoNumber(firstValue, SecodValue, lastValue);

                    }
                }

            }


        }//GetTwoNumber()_end

    }//claass_end
}

②输出结果如下:

猜你喜欢

转载自blog.csdn.net/xiaochenXIHUA/article/details/83650676