首页 > 代码库 > 递归实现阶乘

递归实现阶乘

如果想实现一个阶乘,比如6 * 5 * 4 * 3 * 2 * 1,首先想到的可能是循环遍历。如下:

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入一个数");
            int number = Convert.ToInt32(Console.ReadLine());
            double result = JieCheng(number);
            Console.WriteLine(number.ToString() + "的阶乘结果是:" + result.ToString());
            Console.ReadKey();
        }
 
        public static double JieCheng(int number)
        {
            if (number == 0)
            {
                return 0;
            }
 
            //初始值必须设置为1
            double result = 1;
 
            for (int i = number; i >= 1; i--)
            {
                result = result*i;
            }
            return result;
        }
    }

<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>

但以上的阶乘还有一种实现方式:6 * (6-1) * (6-2) * (6-3) * (6-4) * (6-5) 或 6 * (6-1) * (5-1) * (4-1) * (3-1) * (2-1),也就是说后面数总是由前面的数减1得到的。

 

当实现的逻辑相同,且内部递归方法的参数可以由外部递归方法的参数,经过某种算法而获得,这正是递归登场的时候。

        public static double JieCheng(int number)        {            if (number == 0)            {                return 1;            }            return number * JieCheng(number - 1);        }
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>