编写C#程序以使用递归计算阶乘
在下面的示例中,我们使用递归函数checkFact()查找数字的阶乘-
如果值为1,则由于阶乘为1,则返回1-
if (n == 1) return 1;
如果不是,那么如果您希望值为5,则将在以下迭代中调用递归函数!
Interation1: 5 * checkFact (5 - 1); Interation2: 4 * checkFact (4 - 1); Interation3: 3 * checkFact (3 - 1); Interation4: 4 * checkFact (2 - 1);
要使用递归计算阶乘,您可以尝试运行以下代码,以显示上面的操作-
示例
using System;
namespace Demo {
class Factorial {
public int checkFact(int n) {
if (n == 1)
return 1;
else
return n * checkFact(n - 1);
}
static void Main(string[] args) {
int value = 9;
int ret;
Factorial fact = new Factorial();
ret = fact.checkFact(value);
Console.WriteLine("Value is : {0}", ret );
Console.ReadLine();
}
}
}输出结果
Value is : 362880