構文的には、C++ コードは C# で記述された同じコードと同じです。言語の不一致に不意を突かれないようにしてください。変数が関数の先頭で宣言されていることを考えると、実際には C のように見えます。これは、C++ または C# では厳密には必要ありません。私は、変数を初めて使用するときに変数を宣言し、宣言と初期化を 1 つのステートメントにまとめることを好みますが、それはコードの機能を変更しないスタイル上の好みにすぎません。
コード スニペットの各行にコメントを追加して、これを説明します。
// Declare a function named "Factorial" that accepts a single integer parameter,
// and returns an integer value.
int Factorial(int number)
{
// Declare a temporary variable of type integer
int temp;
// This is a guard clause that returns from the function immediately
// if the value of the argument is less than or equal to 1.
// In that case, it simply returns a value of 1.
// (This is important to prevent the function from recursively calling itself
// forever, producing an infinite loop!)
if(number <= 1) return 1;
// Set the value of the temp variable equal to the value of the argument
// multiplied by a recursive call to the Factorial function
temp = number * Factorial(number - 1);
// Return the value of the temporary variable
return temp;
}
再帰呼び出しとは、関数が同じ関数内から自分自身を呼び出すことを意味します。これが機能するのは、n の階乗が次のステートメントと同等であるためです。
n! = n * (n-1)!
コードがどのように機能するかを理解するための優れた方法の 1 つは、コードをテスト プロジェクトに追加し、デバッガーを使用してコードを 1 ステップ実行することです。Visual Studio は、C# アプリケーションでこれを非常に豊富にサポートしています。関数がどのように再帰的に自身を呼び出すか、各行が順番に実行されるのを観察し、操作が実行されると変数の値が変化するのを観察することさえできます。