C#递归实现:阶乘算法
//求n的阶乘
private static int CalJieCheng(int n)
{
if (n < 0)
{
throw new Exception("请示输入正整数!");
}
if (n < 2)
{
return 1;
}
else if (n > 16)
{
string text = string.Format("结果超出int32的范围:{0},无法显示!",int.MaxValue.ToString());
throw new Exception(text);
}
else
{
return n * Run(n - 1);
}
}
private static int Run(int m)
{
if (m == 1)
{
return 1;
}
return m * Run(m - 1);
}
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("请输入正整数:");
string s = Console.ReadLine();
int n = int.Parse(s);
int reslut = CalJieCheng(n);
Console.WriteLine(s + "的阶乘是:" + reslut.ToString());
}
}
private static int CalJieCheng(int n)
{
if (n < 0)
{
throw new Exception("请示输入正整数!");
}
if (n < 2)
{
return 1;
}
else if (n > 16)
{
string text = string.Format("结果超出int32的范围:{0},无法显示!",int.MaxValue.ToString());
throw new Exception(text);
}
else
{
return n * Run(n - 1);
}
}
private static int Run(int m)
{
if (m == 1)
{
return 1;
}
return m * Run(m - 1);
}
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("请输入正整数:");
string s = Console.ReadLine();
int n = int.Parse(s);
int reslut = CalJieCheng(n);
Console.WriteLine(s + "的阶乘是:" + reslut.ToString());
}
}
本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利
This posting is provided "AS IS" with no warranties, and confers no rights.
This posting is provided "AS IS" with no warranties, and confers no rights.
浙公网安备 33010602011771号