亲宝软件园·资讯

展开

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

人气:0
想了解C# 实现阶乘 (递归,非递归) 实现代码的相关内容吗,在本文为您仔细讲解实现阶乘 (递归,非递归)的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:阶乘,递归,非递归,下面大家一起来学习吧。

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


截图:

加载全部内容

相关教程
猜你喜欢
用户评论