/// <summary> /// 递归方式 /// </summary> /// <param name="n"></param> /// <returns></returns> public static int Fn(int n) { if (Default(n)) return 1; return Fn(n - 1) + Fn(n - 2); } /// <summary> /// 循环方式 /// </summary> /// <param name="n"></param> /// <returns></returns> public static int FnFor(int n) { if (Default(n)) return 1; int first = 1; int second = 1; for (int i = 3; i <= n; i++) { second = first + (first = second); } return second; } /// <summary> /// 默认处理 /// </summary> /// <param name="n"></param> /// <returns></returns> private static bool Default(int n) { if (n <= 0) { throw new Exception("输入的数字必须是大于0的整数"); } return n <= 2; }
时间: 2024-10-12 18:54:03