【问题标题】:c# return value in recursive methodc#递归方法的返回值
【发布时间】:2011-11-07 14:53:26
【问题描述】:

冒着听起来很愚蠢的风险,为什么当条件块等于 true 时,下面的方法返回结果而不是值 1?

public long Recursive(int Input)
{
    if (Input <= 1)
        return 1;
    else
        return Input * Recursive(Input - 1);
}

【问题讨论】:

    标签: c# .net return-value


    【解决方案1】:

    它确实在Input == 1 处返回 1。

    但是返回的1是和之前的调用一起使用的,乘以Input的返回值是和之前的调用一起使用的,再乘以Input的返回值是和之前的调用一起使用的,乘以Input,其返回值与之前的调用一起使用,乘以Input...直到您回到第一次调用Recursive

    尝试看看当您使用值3 调用Recursive 时会发生什么:

    - 输入不是 1,所以它用值 2 调用 Recursive - 输入不是 1,所以它用值 1 调用 Recursive - 输入为 1,返回 1 - 返回 2 * 1 - 返回 3 * 2

    【讨论】:

    • 我明白,也很明显。谢谢,我会在 10 内接受。
    【解决方案2】:

    只看一个简单的例子:Recursive(2)

    invoke Recursive(2)
    if(input <= 1) evaluates to false
    so the else block is executed and the return value is 2 * Recursive(2 - 1)
    invoke Recursive(1)
    if(input <= 1) evaluates to true
    so the return value of Recursive(2 - 1) is 1
    thus the return value of Recursive(2) is 2 * 1 = 2
    

    让我们来解决另一个问题:递归(3)

    invoke Recursive(3)
    if(input <= 1) evalues to false
    so the else block is executed adn the return value is 3 * Recursive(3 - 1)
    but we just showed Recursive(2) evaluates to 2
    so the return value of Recursive(3) is 3 * 2 = 6
    

    【讨论】:

    • 递归+1大故障
    【解决方案3】:

    它没有。正如预期的那样,它返回 1,但是,该返回值随后被传回调用堆栈并被更改。

    【讨论】:

    • 未更改。返回另一个值。
    【解决方案4】:

    它将返回Input的阶乘。

    递归是解决多种类型问题的常用技术。 根据维基百科

    “计算机科学中的递归是一种方法,其中问题的解决方案取决于同一问题的较小实例的解决方案。该方法可以应用于多种类型的问题,并且是计算机科学的中心思想之一” .

    以下方案代码 sn-p 将帮助您了解递归的工作原理。

    【讨论】:

      【解决方案5】:

      为 $ReturnValue1 设置一个监视并使用调试循环查看结果。

      【讨论】:

        猜你喜欢
        • 2021-03-14
        • 1970-01-01
        • 2014-02-27
        • 1970-01-01
        • 1970-01-01
        • 2016-08-03
        • 2017-05-14
        • 1970-01-01
        • 2014-01-24
        相关资源
        最近更新 更多