为什么这个阶乘程序有效?
Why does this factorial program work?
这是 tutorialpoints C# 教程中显示的阶乘程序,我了解递归的基本概念,但我不确定为什么它在这种情况下有效。程序是这样的:
public int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
//calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
在你的递归过程中,你会将 num 的值减 1,当递归停止时,因为 num == 1 那么你将 return 你的递归并乘以每个值。
factorial(5)
-> factorial(4) * 5
-> factorial(3) * 4
-> factorial(2) * 3
-> factorial(1)
最后如果会做:1 * 2 * 3 * 4 * 5 = 120;
这是 tutorialpoints C# 教程中显示的阶乘程序,我了解递归的基本概念,但我不确定为什么它在这种情况下有效。程序是这样的:
public int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
//calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
在你的递归过程中,你会将 num 的值减 1,当递归停止时,因为 num == 1 那么你将 return 你的递归并乘以每个值。
factorial(5)
-> factorial(4) * 5
-> factorial(3) * 4
-> factorial(2) * 3
-> factorial(1)
最后如果会做:1 * 2 * 3 * 4 * 5 = 120;