int main()
{
f(12345);
return 0;
}
void f(long n)
{
cout << n%10;
if(n!=0)
{
f(n/100); cout <<n%10;
}
}
我不明白为什么调用 f(12345) 会打印出“5310135”,我刚开始学习递归,但我不明白它是如何打印出来的。我已经编译并运行了程序,所以我知道它打印的值。我卡在 5310,然后我不知道最后 3 位数字是怎么出现的,有人可以向我解释一下吗?
最佳答案
第二个cout
将在递归展开时执行,即从最后一次递归调用到第一次递归调用。
f(12345)
print 5
f(123) ----------> f(123)
print 5 print 3
f(1) --------> f(1)
print 3 print 1
f(0) -----> f(0)
print 1 print 0
关于c++ - 递归打印 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44744663/