由于StackOverflowException,递归因子终止

时间:2015-11-05 12:04:02

标签: c# recursion factorial

我正在尝试学习递归,并且我试图通过递归而不是循环来进行阶乘,但是我的程序导致"由于StackOverflowException导致进程终止

class RecursionFactorial
{
    public static int n;

    static void Main(string[] args)
    {
        string input;

        Console.WriteLine("Please enter a number to work out the factorial");
        input = Console.ReadLine();
        bool test = int.TryParse(input, out n);
        fact(n);

    }
    public static int fact(int y)
    {
        int count = n;
        if (y <= 1)
        {
            Console.WriteLine(y);
        }
        else
        {
            count = (count * y);
            Console.WriteLine(count);
            fact(y - 1);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

在任何递归中,您必须有案例递归已结束。因此,您必须输入return关键字你的功能。

public static int fact(int y)
{
    if (y <= 1)
    {
        return 1;
    }
    else
    {
        return y * fact(y - 1);
    }
}

答案 1 :(得分:1)

使用此代码修复:

        static void Main(string[] args)
    {
        int n;
        string input;

        Console.WriteLine("Please enter a number to work out the factorial");
        input = Console.ReadLine();
        bool test = int.TryParse(input, out n);

        int factorial = fact(n);
        Console.WriteLine("{0} factorial is {1}", n, factorial);
        Console.ReadLine();

    }
    public static int fact(int y)
    {
        if (y <= 1)
        {
            return 1;
        }
        else
        {
            return y * fact(y - 1);
        }