#include <stdio.h>
void myPrint (int n) {
printf("%d", n/2);
if(n > 0)
myPrint (n - 1);
printf("%d", n);
}
int main (void) {
int count = 4;
myPrint (count);
return 0;
}
这个简单的打印程序打印2110001234,有人请解释为什么最后打印01234。我不知道为什么每次都加1。
答案 0 :(得分:5)
最后,您看到myPrint
的调用与他们发生的顺序相反。
这是查看每次递归调用过程中发生的事情的一种方法。
myPrint(4)
printf("%d", n/2) // Prints 2 because 4/2 = 2
myPrint(n - 1) // Calls myPrint(3)
printf("%d", n/2) // Prints 1 because 3/2 = 1
myPrint(n - 1) // Calls myPrint(2)
printf("%d", n/2) // Prints 1 because 2/2 = 1
myPrint(n - 1) // Calls myPrint(1)
printf("%d", n/2) // Prints 0 because 1/2 = 0
myPrint(n - 1) // Calls myPrint(0)
printf("%d", n/2) // Prints 0 because 0/2 = 0
// Does not execute if statement
printf("%d", n); // Prints 0 because n = 0 at this call
printf("%d", n); // Prints 1 because n = 1 at this call
printf("%d", n); // Prints 2 because n = 2 at this call
printf("%d", n); // Prints 3 because n = 3 at this call
printf("%d", n); // Prints 4 because n = 4 at this call
答案 1 :(得分:3)
myPrint
是递归函数,它打印以下语法:
myPrint(n) -> printf(n/2) ++ myPrint(n-1) ++ printf(n)
每个n>0
都是,而n=0
的语法是
myPrint(0) -> printf("00")
所以n = 4
:
myPrint(4) ->
-> "2" ++ myPrint(3) ++ "4" ->
-> "2" ++ ("1" ++ myPrint(2) ++ "3") ++ "4" ->
-> "21" ++ ("1" ++ myPrint(1) ++ "2") ++ "34" ->
-> "211" ++ ("0" ++ myPrint(0) ++ "1") ++ "234" ->
-> "2110" ++ ("00") ++ "1234" ->
-> "2110001234"
此处++
表示连接。