编写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
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短