C#函数的递归

using System;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            int b = j1(5);
            Console.WriteLine(b);
            int a = j(5);
            Console.WriteLine(a);
        }
       /// <summary>
       /// 循环求阶乘
       /// </summary>
       /// <param name="b"></param>
       /// <returns></returns>
        static int j1(int b)
        {
            int a = 1;
            for (int i = 1; i <= b; i++)
            {
                a = i * a;
            }
            return a;
        }
        /// <summary>
        /// 函数的递归求阶乘
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        static int j(int a)
        {
            int b;
            if (a <= 1)
            {
                return 1;//初始值
            }
            else
            {
                b = a * j(a - 1);//递推关系
            }
            return b;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/BruceKing/p/11820141.html