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 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短