0) myPrint (n - 1); p-6ren">
gpt4 book ai didi

c - 打印程序,请解释输出

转载 作者:行者123 更新时间:2023-11-30 21:14:06 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com