编写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 婶婶拜年祝福语大全简短