簡體   English   中英

由於 StackOverflowException 導致遞歸因子終止

[英]Recursion Factorial terminating due to StackOverflowException

我正在嘗試學習遞歸,並且嘗試通過遞歸而不是循環來執行階乘,但是我的程序導致“進程因 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關鍵字。

public static int fact(int y)
{
    if (y <= 1)
    {
        return 1;
    }
    else
    {
        return y * fact(y - 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);
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM