//C# 求斐波那契数列的前10个数字 :1 1 2 3 5 8 13 21 34 55
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
OutPut4();
}
//方法1,使用while循环
public static void OutPut1()
{
int sum = 0; //输出的值
int num1 = 0;
int num0 = 0;
int i = 0;//计数器
while (i < 10)
{
if (i == 0)
{
sum = num0 = 1;
}
else if (i == 1)
{
sum = num1 = 1;
}
else
{
sum = num1 + num0;
num0 = num1;
num1 = sum;
}
Console.WriteLine(sum);
i++;
}
Console.Read();
}
//方法2,使用for循环
public static void OutPut2()
{
int num = 1;
int prev = 0;
for (int i = 0; i < 10; i++)
{
Console.WriteLine(num.ToString());//在这里输出或者存起来
int temp = num;
num += prev;
prev = temp;
}
Console.Read();
}
//方法3,使用数组
public static void OutPut3()
{
var numArray = new int[10];
int i = 0;
while (i < 10)
{
if (i == 0)
{
numArray[i] = 1;
}
else if (i == 1)
{
numArray[i] = 1;
}
else
{
numArray[i] = numArray[i - 1] + numArray[i - 2];
}
Console.WriteLine(numArray[i]);
i++;
}
Console.Read();
}
//方法4,使用递归循环
public static void OutPut4()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Calc(i));
}
Console.Read();
}
public static int Calc(int num)
{
if (num == 0 || num == 1)
{
return 1;
}
return Calc(num - 1) + Calc(num - 2);
}
}
}