递归函数
给定以下递归函数,神秘(4)会打印什么?
void mysterious(int x) {
if (x == 0) return;
printf(“%d ”, x);
mysterious(x-1);
mysterious(x-1);
}
这是我的调用堆栈:
mysterious(4) => print 4
mysterious(3) => print 3
mysterious(2) => print 2
mysterious(1) => print 1
mysterious(0) => print 0
这是正确的吗?
Given the following recursive function, what would be printed by mysterious(4)?
void mysterious(int x) {
if (x == 0) return;
printf(“%d ”, x);
mysterious(x-1);
mysterious(x-1);
}
Here is my call stack:
mysterious(4) => print 4
mysterious(3) => print 3
mysterious(2) => print 2
mysterious(1) => print 1
mysterious(0) => print 0
Is this correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为每个函数调用都会依次进行 2 个函数调用,所以您可以将递归可视化为一棵“树”,并且您正在树上进行前序遍历。
它看起来像这样:
您的执行顺序是:
这将对应于我们的“树可视化”:
输出为:
Because every function call makes 2 function calls in turn, you can visualize your recursion as a "tree" so to speak, and you are doing a preorder traversal on the tree.
It would look something like this:
The order of execution that you have is:
This would correspond to our "tree visualization" by doing:
The output would be:
为什么不直接用您选择的语言将其输入到编辑器中,编译并运行呢?我选择了 Java,但这只是因为我目前在我的机器上安装了 CygWin - 我更愿意使用 C :-)
这会输出数字:
基本上,发生的情况是,在每个级别,您都会打印出然后该数字用下一个最小的数字调用下一个级别两次(除非它达到零)。
下图有望更好地说明这一点,其中不同的符号代表不同的层:
Why don't you just type it in to an editor in your language of choice, compile it and run? I chose Java but that's just because I'm between CygWin installs on my box at the moment - I'd much rather be using C :-)
This outputs the numbers:
Basically, what's happening is that, at each level, you print out the number then call the next level twice with the next lowest number (unless it's reached zero).
The following diagram will hopefully illustrate this better, with different symbols representing different layers:
不,这是
因为 0 会导致函数提前返回,并且由于两次调用。
No, it will be
because 0 will cause the function to return earlier and because of that double-call.
不会。它不会打印
0
因为当x==0
时它会返回另外,因为你有
它会打印 (Fixed)
< code>mysterious(x-1); 不会更改
x
的值。它只是再次调用mysterious()
,这次的值为x-1
No. It won't print
0
cause whenx==0
it will returnAlso, since you have
it will print (Fixed)
mysterious(x-1);
doesnt change the value ofx
. it just callsmysterious()
again, this time with the valuex-1