欢迎来到萧静默的博客

书山有路勤为径,学海无涯苦作舟。

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;
        }
    }
}

 

posted @ 2019-11-08 14:39  萧静默  阅读(533)  评论(0编辑  收藏  举报