Runtime exception, recursion too deep

后端 未结 12 1046
余生分开走
余生分开走 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:48

    This woudl be the non recursive variant:

            private double CalculatePi(int maxRecursion)
        {
            return 2 * CalculatePi2(maxRecursion, 1);
        }
    
        private double CalculatePi2(int maxRecursion, int i)
        {
            double product = 1;
            while (i < maxRecursion)
            {
                product = product * (1f + i / (2.0f * i + 1f));
                i++;
            }
            return product;
        }
    

提交回复
热议问题