C#阶乘
要在C#中计算阶乘,可以使用while循环和循环遍历直到数字不等于1。
这里n是您想要阶乘的值-
int res = 1;
while (n != 1) {
res = res * n;
n = n - 1;
}以上,假设我们要5!(5阶乘)
为此,n=5,
循环迭代1-
n=5 res = res*n i.e res =5;
循环迭代2-
n=4 res = res*n i.e. res = 5*4 = 20
循环迭代3-
n=3 res = res*n i.e. res = 20*3 = 60
示例
这样,所有迭代将得出5的结果为120!如以下示例所示。
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
热门推荐
10 同事换单位简短祝福语
11 谢谢朋友的祝福语简短
12 立秋节气简短祝福语
13 新房祝福语简短10字
14 长辈新年祝福语大全简短
15 新年给大家简短祝福语
16 生日祝福语简短独特姑姑
17 芭比的婚礼祝福语简短
18 邀请新人祝福语简短英文