Recursion Factorial terminating due to StackOverflowException

◇◆丶佛笑我妖孽 提交于 2019-12-20 08:06:15

问题


I am trying to learn recursion and I am attempting to do factorial's via recursion instead of loops, but my program is causing "Process is terminated due to 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);
        }
    }
}

回答1:


In any Recursion you must have a case,where your recursion is ended.So you must enter return keyword to your function.

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



回答2:


fixed with this code:

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


来源:https://stackoverflow.com/questions/33544063/recursion-factorial-terminating-due-to-stackoverflowexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!