「フィボナッチ数/C Sharp」の版間の差分
< フィボナッチ数
ナビゲーションに移動
検索に移動
imported>Administrator |
imported>GamerBook (→記述例 1) |
||
(2人の利用者による、間の3版が非表示) | |||
2行目: | 2行目: | ||
== 記述例 1 == | == 記述例 1 == | ||
− | + | 古風な記述例。 | |
+ | 一応、[[末尾再帰]]にはなっている。 | ||
+ | <source lang="csharp"> | ||
+ | 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) )); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </source> | ||
+ | |||
+ | == 記述例 2 == | ||
+ | [[ラムダ式]]を使った記述方法。 | ||
<source lang="csharp"> | <source lang="csharp"> | ||
using System; | using System; | ||
13行目: | 47行目: | ||
public static void Main(string[] args) | public static void Main(string[] args) | ||
{ | { | ||
− | Console.WriteLine( fib( | + | for (int x = 0; x < 16; x++) |
+ | { | ||
+ | Console.WriteLine("fib({0}) = {1}", x, fib(x) ); | ||
+ | } | ||
} | } | ||
} | } | ||
23行目: | 60行目: | ||
== 参考文献 == | == 参考文献 == | ||
− | < | + | <references/> |
== 外部リンク == | == 外部リンク == | ||
{{stub}} | {{stub}} |
2012年12月6日 (木) 04:34時点における最新版
記述例 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) );
}
}
}
関連項目[編集 | ソースを編集]
参考文献[編集 | ソースを編集]