在C#中,可以通過多種方法實現斐波那契數列
using System;
class Program
{
static void Main()
{
int n = 10; // 輸出前10個斐波那契數
for (int i = 0; i < n; i++)
{
Console.Write(FibonacciRecursive(i) + " ");
}
}
static int FibonacciRecursive(int n)
{
if (n <= 1)
{
return n;
}
else
{
return FibonacciRecursive(n - 1) + FibonacciRecursive(n - 2);
}
}
}
using System;
class Program
{
static void Main()
{
int n = 10; // 輸出前10個斐波那契數
for (int i = 0; i < n; i++)
{
Console.Write(FibonacciIterative(i) + " ");
}
}
static int FibonacciIterative(int n)
{
if (n <= 1)
{
return n;
}
int a = 0, b = 1, result = 0;
for (int i = 2; i <= n; i++)
{
result = a + b;
a = b;
b = result;
}
return result;
}
}
using System;
class Program
{
static void Main()
{
int n = 10; // 輸出前10個斐波那契數
int[] fibArray = new int[n];
FibonacciDynamic(n, fibArray);
for (int i = 0; i < n; i++)
{
Console.Write(fibArray[i] + " ");
}
}
static void FibonacciDynamic(int n, int[] fibArray)
{
fibArray[0] = 0;
if (n > 1)
{
fibArray[1] = 1;
for (int i = 2; i < n; i++)
{
fibArray[i] = fibArray[i - 1] + fibArray[i - 2];
}
}
}
}
這些示例展示了如何在C#中實現斐波那契數列。你可以根據需要選擇合適的方法。