Recursion Factorial terminating due to StackOverflowException

前端 未结 2 1749
無奈伤痛
無奈伤痛 2021-01-29 14:29

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 StackOverflowExcep

相关标签:
2条回答
  • 2021-01-29 14:53

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-29 15:06

    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);
            }
    
    0 讨论(0)
提交回复
热议问题