C# 递归调用示例:计算阶乘
下面是一个用 C# 写的递归调用的样例,用于计算一个数的阶乘:
using System;
class Program
{
static void Main(string[] args)
{
int num = 5;
int result = Factorial(num);
Console.WriteLine('Factorial of {0} is {1}', num, result);
}
static int Factorial(int n)
{
if (n == 0)
return 1;
else
return n * Factorial(n - 1);
}
}
该程序通过递归的方式计算一个数的阶乘。在主函数中,我们定义了一个整数 num,并将其设为 5。然后,我们调用 Factorial 函数,并将 num 作为参数传递给它。Factorial 函数递归地调用自身,直到 n 等于 0 时,返回 1。如果 n 不为 0,则返回 n 乘以 Factorial(n - 1) 的结果。最终,程序输出了 5 的阶乘的结果。
原文地址: http://www.cveoy.top/t/topic/nnIu 著作权归作者所有。请勿转载和采集!