用 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("
Factorial 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

更新日期: 2020-06-19

614 人瀏覽

開啟您的職業生涯

完成課程,獲得認證

開始
廣告