Runtime exception, recursion too deep

后端 未结 12 1038
余生分开走
余生分开走 2020-12-19 04:59

I converted the pseudo-code here into C#, and have it recursively repeat 10,000 times. But I get a C# runtime error, StackOverflow Exception after 9217

12条回答
  •  心在旅途
    2020-12-19 05:53

    The "c# compiler" will compile this fine. At runtime, however, you may end up with a StackOverflow exception (on my machine, 10,000 works fine, but dies later).

    This is not an "infinite recursion exception" - stack overflow is exactly what it says; calling a method means putting information on the stack and removing it when the call returns. You have 10,000 calls and none have returned, so the stack is full and the exception is thrown.

    You can fix this fairly easily in this particular case by removing the recursion and running iteratively. In the general case, there are ways to remove recursion via iteration, tail-recursion optimization, and continuation passing.

    Here's a quick direct translation to an iterative style:

    private static double CalculatePi(int maxRecursion)
            {
                double result = 1;
                for (int i = maxRecursion -1; i >= 1; i-- )
                {
                    result = 1 + i / (2.0 * i + 1) * result;
                }
                return result * 2;
            }
    

提交回复
热议问题