#include
using namespace std;
int repeat(int m)
{
cout << m;
if (m>1)
{
repeat(--m);
cout << m << endl;
m--;
}
return 1;
}
int main()
{
int h = 5;
repeat(h);
}
递归到终 repeat()函数有return1 返回到repeat(--m) repeat(--m)有return 1
为什么不返回repeat(int m) 而是向下走 求详细的答案谢谢
------Start------
|repeat(5)
|---cout << 5;
|---repeat(4)
| |---cout << 4;
| |---repeat(3)
| | |---cout << 3;
| | |---repeat(2)
| | | |---cout << 2;
| | | |---repeat(1)
| | | | |---cout << 1;
| | | | |---return 1; // 退出
| | | |---cout << 1 << endl;
| | | |---m--;
| | | |---return 1; // 退出
| | |---cout << 2 << endl;
| | |---m--;
| | |---return 1; // 退出
| |---cout << 3 << endl;
| |---m--;
| |---return 1; // 退出
|---cout << 4 << endl;
|---m--;
|---return 1; // 退出
函数永远在执行完之后返回它的调用者。递归也不例外。递归只是自己调用自己而已。
对于外侧的repeat函数来说,内侧的repeat(--m);调用完,自然执行后面的cout<<m<<endl;