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 教师闺蜜祝福语简短