在C#中计算阶乘的三种不同方法
要在C#中计算阶乘,可以使用以下三种方式之一-
用for循环计算阶乘
示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace factorial {
class Test {
static void Main(string[] args) {
int i, res;
int value = 5;
res = value;
for (i = value - 1; i >= 1; i--) {
res = res * i;
}
Console.WriteLine("\nFactorial of "+value+" = "+res);
Console.ReadLine();
}
}
}输出结果
Factorial of 5 = 120
用while循环计算阶乘
示例
using System;
namespace MyApplication {
class Factorial {
public int display(int n) {
int res = 1;
while (n != 1) {
res = res * n;
n = n - 1;
}
return res;
}
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
使用递归计算阶乘
示例
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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短