要在 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
这样,所有迭代的结果都是 120 for 5!如下例所示。
现场演示
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
以上就是C# 阶乘的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号