什么是 斐波那契 豎列:
斐波那契數(shù)列(Fibonacci sequence),又稱黃金分割數(shù)列 [1],因數(shù)學(xué)家萊昂納多·斐波那契(Leonardo Fibonacci)以兔子繁殖為例子而引入,故又稱“兔子數(shù)列”,
其數(shù)值為:1、1、2、3、5、8、13、21、34……
在數(shù)學(xué)上,這一數(shù)列以如下遞推的方法定z義:
F(0)=1,F(xiàn)(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*)。
使用 IEnumerable 接口可以實(shí)現(xiàn)斐波那契數(shù)列的生成。IEnumerable 接口提供了一個(gè)迭代器方法 GetEnumerator(),通過(guò)實(shí)現(xiàn)該方法可以返回一個(gè)迭代器對(duì)象,該對(duì)象可以用于遍歷集合中的元素。
下面是使用 IEnumerable 實(shí)現(xiàn)斐波那契數(shù)列生成的示例代碼:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-853512.html
using System.Collections;
namespace Temp
{
internal class Program
{
static void Main(string[] args)
{
Fibonacci fibonacci = new Fibonacci(10);
foreach (var number in fibonacci)
{
Console.WriteLine(number);
}
}
}
/// <summary>
/// 斐波那契豎列
/// </summary>
public class Fibonacci : IEnumerable
{
private int _count;
public Fibonacci(int count)//使用構(gòu)造函數(shù)傳參
{
this._count = count;
}
public IEnumerator GetEnumerator()
{
int a = 0;
int b = 1;
for (int i = 0; i < _count; i++)
{
yield return a;
int temp = a;
a = b;
b = temp + b;
}
}
}
/// <summary>
/// 自定義異常類
/// </summary>
public class CustomException : Exception
{
public CustomException(string message) : base(message)
{
//在此處添加自定義邏輯
}
}
}
yield return是一種用于創(chuàng)建迭代器的關(guān)鍵字。它可以在方法中暫停執(zhí)行,并返回一個(gè)序列中的下一個(gè)元素。通過(guò)使用yield return,我們可以按需生成序列的元素,而不需要一次性生成所有元素。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-853512.html
到了這里,關(guān)于C#面:使用 IEnumerable 實(shí)現(xiàn)斐波那契數(shù)列生成的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!