由于StackOverflowException,递归阶乘终止 [英] Recursion Factorial terminating due to StackOverflowException

查看:84
本文介绍了由于StackOverflowException,递归阶乘终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

在任何递归中,您都必须具有情况,其中您的递归结束.因此您必须在函数中输入return关键字.

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

这篇关于由于StackOverflowException,递归阶乘终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆