版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiegemena/article/details/80005986
列数的规则如下: 1、1、2、3、5、8、13、21、34…… 求第30位数是多少
分析:从第二个数开始,每位等于前两个数相加
递归:
public static void Do()
{
int endnum = Foo(30);
Console.WriteLine(endnum.ToString());
}
public static int Foo(int index)
{
if (index <= 0)
{
return 0;
}
else if (index == 1 || index == 2)
{
return 1;
}
return Foo(index - 1) + Foo(index - 2);
}
循环:
public static void Do2()
{
Console.WriteLine(Foo2(30).ToString());
}
public static int Foo2(int positionIndex)
{
if (positionIndex <= 0)
{
throw new Exception("处理不了!");
}
else if (positionIndex <= 2)
{
return 1;
}
int index1 = 1;
int index2 = 1;
int index = 0;
for (int i = 2; i < positionIndex; i++)
{
index = index1 + index2;
index1 = index2;
index2 = index;
}
return index;
}