这个递归在C#中有什么问题?

时间:2017-09-14 18:31:08

标签: c# recursion

我想编写一个简单的递归,用三次替换方法,完成后,返回函数运行的次数。

我执行一个调用方法,通过委托参数提供另一个方法,并打印一个简单的消息三次。

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public delegate void funct(string msg);

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public static void funct(string msg)
        {
            MessageBox.Show(msg);
        }

        public static int caller(funct f, string msg, int max, int count = 0)
        {
            if (count < max)
            {
                funct(msg);
                caller(f, msg, max, ++count);
            }

            return count;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            int a = caller(funct, "LOL", 3);
            //should return value 3, but returned with value 1

        }
    }
}

返回值总是错误的,因为我回到了1而不是3。

4 个答案:

答案 0 :(得分:3)

这是因为你没有传递递归链的计数值。

public static int caller(funct f, string msg, int max, int count = 0)
{
    if (count < max)
    {
        fugg(msg);
        return caller(f, msg, max, ++count);
    }

    return count;
}

答案 1 :(得分:1)

请记住,在每次调用函数count时,您都没有更改caller的值。因此,每次调用函数时,它只是返回当前值count,在执行结束时只有count加1。在caller的第一次调用中,count的值从0变为1,随后的caller递归调用将不再影响count的值。

也许您应该重写caller

    public static int caller(funct f, string msg, int max, int count = 0)
    {
        if (count < max)
        {
            funct(msg);
            count = caller(f, msg, max, count + 1);
        }

        return count;

    }   

答案 2 :(得分:1)

您将count的值传递给caller的recursve调用。这是一个按值传递,因此即使您在递归调用中更改count的值,也不会传回更新的值。您只需在返回之前更新调用者中count的值:

    public static int caller(funct f, string msg, int max, int count = 0)
    {
        if (count < max)
        {
            funct(msg);
            count = caller(f, msg, max, ++count);
        }

        return count;
    }

答案 3 :(得分:0)

了解堆栈的工作原理:

Level 1:
Count gets initialized as 0;
Msgbox shows
Calls itself
    Level 2:
    Count gets passed in as 1;
    Msgbox shows
    Calls itself
        Level 3
        Count gets passed in as 2;
        Msgbox shows
        Calls itself
            Level 4
            Count gets passed in as 3;
            Count is too high;
            returns 3;
        Returns count (for its scope), which is 3
    Returns count (for its scope), which is 2
Returns count (for its scope), which is 1.

你有两种简单的方法来修复它。一种是改变变量,使其成为参考。但说实话,我更喜欢将函数的retVal返回到链中,如下所示:

    public static int caller(funct f, string msg, int max, int count = 0)
    {
        if (count < max)
        {
            funct(msg);
            return caller(f, msg, max, ++count);
        }

        return count;

    }