求c#输出斐波那契数列前20项1、1、2、3、5、8。。每行输出5个

求c#输出斐波那契数列前20项1、1、2、3、5、8、13、21、34。。每行输出5个,f(n)=1。。。。。。。。。。。(当n=1、2时)f(n)=f(n-1)+f(n-2)。。。。。。(当n>2时)

C#程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int f1 = 1;
            int f2 = 1;
            int i;

            System.Console.Write(f1 + " " + f2 + " ");

            for (i = 3; i <= 20; i++)
            {
                f2 += f1;
                f1 = f2 - f1;
                if(i % 5 == 0)
                    System.Console.WriteLine(f2 + " ");
                else
                    System.Console.Write(f2 + " ");
            }

        }
    }
}


输出:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-07-29
label1.Text = string.Empty;
int[] intarray = new int[20];
for (int i = 0; i < intarray.Length; i++)
{

if (i - 2 < 0)//防止数组索引为负数
intarray[i] = 1;
else
intarray[i] = intarray[i - 2] + intarray[i - 1];
label1.Text += intarray[i].ToString() + " ";
if (i % 5 == 0 && i != 0)//防止第一次i=0的时候换行
label1.Text += "\n";
}
第2个回答  2013-07-29
递归算法: int GetFabbonanci(int num){ if (num==0||num==1) return 1; else return GetFabbonanci(num-2)+GetFabbonanci(num-1);} 主函数:for (int i =1; i<21;++i){ if (i%5==0) Console.WriteLine(); Console.Write(GetFabbonanci(i)+" ");}
第3个回答  2013-07-29
int i, a, b, c = 0,n=0;
a = 1; b = 1;
n=2;
Console.Write(a.ToString ()+" ");
Console.Write(b.ToString()+" ");
for (i = 3; i <= 20; i++)
{
c = a + b; a = b; b = c;
Console.Write(c.ToString()+" ");
n++;
if (n % 5 == 0) Console.WriteLine();
}
Console.ReadLine();本回答被网友采纳
相似回答