跟踪递归函数时出现问题

Trouble tracking recursive function

本文关键字:问题 递归函数 跟踪      更新时间:2023-10-16

我有这样的代码,它输出:10 5 16 8 4 2 11然而,我不知道11是从哪里来的,因为当追踪时,我得到了以下信息:

H(10)
H(5)
1+H(16) //does this result in 17?
H(8)
H(4)
H(2)
H(1) -> returns 0

此外,1+H(16(中的(1(会发生什么?因此,我的n个值的输出不应该是:10 5 17 8 4 2 1

#include <iostream>
using namespace std;
int H ( int n ) {
cout << " " << n<<" ";
if ( n == 1 ) return 0;
if ( n%2 != 0 ) return 1 + H ( 3*n + 1 );
else return H ( n/2 );
} 
int main() {
//   for ( int i=0; ++i<=20; )
//     cout << H(i) << endl;
cout << H(10) << endl;
}

在递归结束时,函数打印1,然后堆栈弹出所有内容,main打印返回值1(递归结束时返回0,只有对H(5(的调用将结果加1(,因此打印11