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

时间:2021-05-20

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

截图:

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章