我们如何递归调用C#方法?
若要递归调用C#方法,可以尝试运行以下代码。在这里,数字的阶乘是我们使用递归函数找到的display()。
如果值为1,则由于阶乘为1,因此返回1。
if (n == 1) return 1;
如果不是,那么如果您想要5的值,则将在以下迭代中调用递归函数!
Interation1: 5 * display(5 - 1); Interation2: 4 * display(4 - 1); Interation3: 3 * display(3 - 1); Interation4: 4 * display(2 - 1);
以下是递归调用C#方法的完整代码。
示例
using System;
namespace MyApplication {
class Factorial {
public int display(int n) {
if (n == 1)
return 1;
else
return n * display(n - 1);
}
static void Main(string[] args) {
int value = 5;
int ret;
Factorial fact = new Factorial();
ret = fact.display(value);
Console.WriteLine("Value is : {0}", ret );
Console.ReadLine();
}
}
}输出结果
Value is : 120
热门推荐
3 祝福语简短古诗词
10 好朋友夫妻祝福语简短
11 教练生日祝福语 简短独特
12 发廊元旦祝福语大全简短
13 对生活祝福语简短精辟
14 入学祝福语简短走心
15 祝福语写给自己的简短
16 公司上班祝福语大全简短
17 婆婆生日祝福语简短的
18 舅妈生日红包祝福语简短