【发布时间】: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
冒着听起来很愚蠢的风险,为什么当条件块等于 true 时,下面的方法返回结果而不是值 1?
public long Recursive(int Input)
{
if (Input <= 1)
return 1;
else
return Input * Recursive(Input - 1);
}
【问题讨论】:
标签: c# .net return-value
它确实在Input == 1 处返回 1。
但是返回的1是和之前的调用一起使用的,乘以Input的返回值是和之前的调用一起使用的,再乘以Input的返回值是和之前的调用一起使用的,乘以Input,其返回值与之前的调用一起使用,乘以Input...直到您回到第一次调用Recursive。
尝试看看当您使用值3 调用Recursive 时会发生什么:
【讨论】:
只看一个简单的例子: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,但是,该返回值随后被传回调用堆栈并被更改。
【讨论】:
它将返回Input的阶乘。
递归是解决多种类型问题的常用技术。 根据维基百科:
“计算机科学中的递归是一种方法,其中问题的解决方案取决于同一问题的较小实例的解决方案。该方法可以应用于多种类型的问题,并且是计算机科学的中心思想之一” .
以下方案代码 sn-p 将帮助您了解递归的工作原理。
【讨论】:
为 $ReturnValue1 设置一个监视并使用调试循环查看结果。
【讨论】: