Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 계승을 계산하는 세 가지 다른 방법


C#에서 계승을 계산하려면 다음 세 가지 방법 중 하나를 사용할 수 있습니다. -

for 루프로 계승 계산

예시

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace factorial {
   class Test {
      static void Main(string[] args) {
         int i, res;
         int value = 5;
         res = value;
         for (i = value - 1; i >= 1; i--) {
            res = res * i;
         }
         Console.WriteLine("\nFactorial of "+value+" = "+res);
         Console.ReadLine();
      }
   }
}

출력

Factorial of 5 = 120

while 루프로 계승 계산

예시

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

재귀를 사용하여 계승 계산

예시

using System;
namespace MyApplication {
   class Factorial {
      public int display(int n) {
         if (n == 1)
            return 1;
         else
            return n * display(n - 1);
      }
      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