我们如何递归调用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
热门推荐
10 兄弟的结婚祝福语简短
11 收到公公生日祝福语简短
12 高考毕业祝福语简短励志
13 牙医生日祝福语简短
14 父亲简短结婚祝福语大全
15 年底老板祝福语简短的
16 初八的祝福语简短
17 考试祝福语简短给对象
18 幼儿住院祝福语老师简短