使用递归计算C#中的factorial

时间:2016-11-11 20:59:34

标签: c# recursion

我知道如何使用循环计算阶乘。下面是循环的代码,但是我通过递归来获取错误,下面是代码可以有人建议

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

1 个答案:

答案 0 :(得分:2)

您的通话名称不等于您的方法名称。

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