在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#中实现斐波那契数列。你可以根据需要选择合适的方法。