在c#中使用递归计算阶乘
本文关键字:递归计算 阶乘 | 更新日期: 2023-09-27 18:17:26
我知道如何使用循环计算阶乘。下面是循环的代码,但我得到一个错误,而做它的递归。下面是两个代码示例。我该如何解决这个问题?
namespace factorial
{
class Program
{
static void Main(string[] args)
{
int i, number, fact;
Console.WriteLine("Enter the Number");
number = int.Parse(Console.ReadLine());
fact = number;
for (i = number - 1; i >= 1; i--)
{
fact = fact * i;
}
Console.WriteLine("'nFactorial of Given Number is: "+fact);
Console.ReadLine();
}
}
}
使用递归的阶乘:
是否有什么地方我错了?我什么时候用递归计算它?
阶乘使用循环:
public double factorial_Recursion(int number)
{
if (number == 1)
return 1;
else
return number * factorial_recursion(number - 1);
}
public double factorial_WhileLoop(int number)
{
double result = 1;
while (number != 1)
{
result = result * number;
}
return result;
}
您的调用名不等于您的方法名:
factorial_Recursion is the method name.
factorial_recursion is the call.
这个为我工作:
namespace Testing
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(factorial_Recursion(5));
Console.WriteLine("press any Key");
Console.ReadLine();
}
public static double factorial_Recursion(int number)
{
if (number == 1)
return 1;
else
return number*factorial_Recursion(number - 1);
}