欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 实现阶乘 (递归,非递归) 实现代码

程序员文章站 2023-12-16 10:07:10
//main:复制代码 代码如下:using system;using system.collections.generic;using system.linq;using...

//main:

复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;

namespace factorial
{
    class program
    {
        static void main(string[] args)
        {
            function obj = new function();
            console.writeline("would you like to know which number of factorial:");
            int number = convert.toint32(console.readline());
            console.writeline();
            console.write("the fibonacci of {0} is:{1}", number, obj.factorial(number));
            console.writeline();
            console.write("the factorialrecursion of {0} is:{1}", number, obj.factorialrecursion(number));
            console.readkey();
        }
    }
}


 //class:
 
复制代码 代码如下:

 using system;
using system.collections.generic;
using system.linq;
using system.text;

namespace factorial
{
    class function
    {
        /// <summary>
        /// factorial定义为:
        ///      ┌ 1        n=0      
        ///   n!=│
        ///      └ n(n-1)!  n>0
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public int factorial(int number)
        {
            if (number != 0)
            {
                return number * factorial(number - 1);
            }
            else if (number == 0)
            {
                return 1;
            }
            return number;
        }

        public int factorialrecursion(int number)
        {
            int f = 1;
            for (int i = 1; i <= number; i++)
            {
                f *= i;
            }
            return f;
        }
    }
}


截图:
C# 实现阶乘 (递归,非递归) 实现代码

上一篇:

下一篇: