#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。

最佳答案

最后,您会看到以相反的顺序调用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

关于c - 打印程序,请说明输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34551167/

10-13 07:40