「フィボナッチ数/C Sharp」の版間の差分

提供: MonoBook
ナビゲーションに移動 検索に移動
imported>Administrator
imported>GamerBook
 
(同じ利用者による、間の1版が非表示)
2行目: 2行目:
  
 
== 記述例 1 ==
 
== 記述例 1 ==
 +
古風な記述例。
 +
一応、[[末尾再帰]]にはなっている。
 
<source lang="csharp">
 
<source lang="csharp">
 
using System;
 
using System;
34行目: 36行目:
  
 
== 記述例 2 ==
 
== 記述例 2 ==
 +
[[ラムダ式]]を使った記述方法。
 
<source lang="csharp">
 
<source lang="csharp">
 
using System;
 
using System;

2012年12月6日 (木) 04:34時点における最新版

C#によるフィボナッチ数の記述例。

記述例 1[編集 | ソースを編集]

古風な記述例。 一応、末尾再帰にはなっている。

using System;

class AppMain 
{
    static int fib(int x)
    {
        if (x <= 0) 
        {
            return 0;
        }
        else if (x <= 2) 
        {
            return 1;
        }
        else 
        {
            return fib(x - 1) + fib(x - 2);
        }
    }

    public static void Main(string[] args) 
    {
        for (int x = 0; x < 16; x++) 
        {
            Console.WriteLine("fib({0}) = {1}", x, fib(x) ));
        }
    }
}

記述例 2[編集 | ソースを編集]

ラムダ式を使った記述方法。

using System;

class AppMain 
{
    static Func<int, int> fib = x => 
        (x <= 2) ? 1 : fib(x - 1) + fib(x - 2);

    public static void Main(string[] args) 
    {
        for (int x = 0; x < 16; x++) 
        {
            Console.WriteLine("fib({0}) = {1}", x, fib(x) );
        }
    }
}

関連項目[編集 | ソースを編集]

参考文献[編集 | ソースを編集]


外部リンク[編集 | ソースを編集]