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 舅舅大婚文案祝福语简短