c#斐波那契数列(Fibonacci)(递归,非递归)实现代码
本文导语: //Main 代码如下:using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace Fibonacci{ class Program { static void Main(string[] args) { Console.WriteLine("Would you like to know which Fibonacci Num...
//Main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Fibonacci
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Would you like to know which Fibonacci Numbers:");
int number = Convert.ToInt32(Console.ReadLine());
//
Function obj = new Function();
Console.WriteLine();
Console.Write("The {0} Fibonacci number is:{1}", number, obj.Fibonacci(number));
//
Console.WriteLine();
Function obj2 = new Function(number);
Console.Write("The {0} Fibonacci number is:{1}", number, obj2.BottomUpNotRecursion(number));
//
Console.WriteLine();
Console.Write("The {0} Fibonacci number is:{1}", number, obj2.TopDownRecursion(number));
Console.ReadKey();
}
}
}
//Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Fibonacci
{
class Function
{
private int[] array;
public Function()
{
}
///
/// Function
///
///
public Function(int length)
{
if (length > 0)
{
array = new int[length + 1];
array[0] = 1;
array[1] = 1;
}
if (length == 0)
{
array = new int[1];
array[0] = 1;
}
}
///
/// Fibonacci数列定义为:
/// 无穷数列1,1,2,3,5,8,13,21,34,55,……
/// ┌ 1 n=0
/// F(n)=│ 1 n=1
/// └ F(n-1)+F(n-2) n>1
///
/// 第几个斐波那契数
///
public int Fibonacci(int number)
{
if (number