Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 递归函数_C_Recursion - Fatal编程技术网

C 递归函数

C 递归函数,c,recursion,C,Recursion,给定以下递归函数: // Pre-condition: y is non-negative. int mysterious(int x, int y) { if (y == 0) return x; return 2*mysterious(x, y-1); } 神秘(3,2)的返回值是多少 这是我的调用堆栈: return 2*mysterious(3, 2-1) => 2*3 => 6, 2*1 => mysterious(6,2) return 2*mys

给定以下递归函数:

// Pre-condition: y is non-negative.
int mysterious(int x, int y) {
    if (y == 0) return x;
    return 2*mysterious(x, y-1);
}
神秘(3,2)的返回值是多少

这是我的调用堆栈:

return 2*mysterious(3, 2-1) => 2*3 => 6, 2*1 => mysterious(6,2)
return 2*mysterious(6, 2-1) => 6*2 => 12, 2*2 => mysterious(12, 2)
但看起来y永远不会达到0。我做错了什么

mysterious(3, 2) = 2 * mysterious(3, 1) = 2 * 2 * mysterious(3, 0) = 2 * 2 * 3 = 12 神秘的(3,2) =2*神秘(3,1) =2*2*3(0) = 2 * 2 * 3 = 12
如果你扩大这个电话,你有效地

(2*(2*(3))) == 12

Y只会减少(每次调用减少1),因此该函数显然是递归的,并且应该在每次调用神秘时终止(一次由您调用,两次由递归调用),Y会减少1

所以,你得到了(神秘的)

3.2
31
30

最终值为12(3*2*2)

x
永远不会被修改,但是每次递归调用
y
都会减少1,当到达地面子句(
如果y==0
)时,它会返回x(第一次调用的值是3)

它就是

x * 2**y


因此,对于
y

的任何值,都可以很好地定义递归。要理解递归,必须首先理解递归。请参阅我对这个问题的评论:
x * 2**y
mysterious(x, y) == x*pow(2, y)