在加某个数值群的时候,要求求n位以后的斐波那契数列。
已知,斐波那契数列为1,1,2,3,5,8,13,21,34,55,89,144, ……
即最后1位为前两位之和。所以可以得出算法脚本如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public int num;
// Start is called before the first frame update
void Start()
{
}
void CreatNum(int _a, int _b, int _d)
{
var _c = _a + _b;
_a = _b;
_b = _c;
_d --;
Debug.Log(_a + " " + _b + " " + _c + " " + _d);
if (_d <= 1) Debug.LogError(_c);
else CreatNum(_a, _b, _d);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
CreatNum(0, 1, num);
}
}
拿脚本验证下: