鉴于此代码:
void recursion(int x) {
if (x > 0) {
recursion(x-1);
printf("%d", x);
}
}
使用:
recursion(5);
为什么打印12345
?我逻辑上遵循我认为会打印43210
答案 0 :(得分:3)
只需遵循代码所经历的步骤(使用调试器即可实时查看):
recursion(5);
if (5 > 0) recursion(4);
if (4 > 0) recursion(3);
if (3 > 0) recursion(2);
if (2 > 0) recursion(1);
if (1 > 0) recursion(0);
if (0 > 0) { // false, so if body skipped and function simply returns}
printf("%d", 1); // The next statement after the call recursion(0)
printf("%d", 2); // The next statement after the call recursion(1)
printf("%d", 3); // The next statement after the call recursion(2)
printf("%d", 4); // The next statement after the call recursion(3)
printf("%d", 5); // The next statement after the call recursion(4)
答案 1 :(得分:2)
x = 5
时,它会调用recursion(4)
;当x=4
时,它会调用recursion(3)
等。当它最终调用recursion(0)
时,条件为false,函数返回时不做任何操作。此时,它返回到recursion(1)
的调用,在此处打印x
的当前值(1),然后返回recursion(2)
等。