Để tính giai thừa trong C #, bạn có thể sử dụng vòng lặp while và lặp lại cho đến khi số không bằng 1.
Đây là giá trị mà bạn muốn giai thừa -
int res = 1;
while (n != 1) {
res = res * n;
n = n - 1;
} Ở trên, giả sử chúng tôi muốn có 5! (5 giai thừa)
Vì vậy, n =5,
Lặp lại lặp lại 1 -
n=5 res = res*n i.e res =5;
Lặp lại vòng lặp 2 -
n=4 res = res*n i.e. res = 5*4 = 20
Lặp lại lặp lại 3 -
n=3 res = res*n i.e. res = 20*3 = 60
Ví dụ
Theo cách này, tất cả các lần lặp sẽ cho kết quả là 120 cho 5! như thể hiện trong ví dụ sau.
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();
}
}
} Đầu ra
Value is : 120