[C#]利用遞迴計算n!階乘

  • 36319
  • 0
  • 2010-08-02

利用遞迴計算n!階乘

很多學校作業與書上範本,一說到遞迴的範例,就會想到計算n!階乘,在這裡提供一個範例程式給我的學生

程式碼

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, result;
            Console.Write("請輸入n(n>0) : ");
            n = Convert.ToInt16(Console.ReadLine());
            result = n_step(n);
            Console.Write("result : ");
            Console.WriteLine(result);
        }


        public static int n_step(int n)
        {
            switch (n)
            {
                case 1:
                    return 1;
                default:
                    return n * n_step(n - 1);
            }


        }

    }

}

執行結果