在C++中跟踪递归阶乘函数

Tracing a recursive factorial function in C++?

本文关键字:阶乘 函数 递归 跟踪 C++      更新时间:2023-10-16

点运动有困难,假设我有:

#include <iostream>
using namespace std;
int factorialFinder(int x) {
    if (x==1) {
        return 1;
    }else{
        return x*factorialFinder(x-1);
    }
}
int main()
{
    cout << factorialFinder(5) << endl;
}

你会如何追踪这一点?例如:

Put in 5 into the factorialFinder function.
if (5 == 1) (False, so skip)
returns 5 times factorialFinder(5-1)
this means returns 5 times factorialFinder(4)
this means go back to function
if (4 == 1) (False, so skip)
returns 4 times factorialFinder(4-1)
...etc.

现在,如果您按照我的逻辑,我的问题就在我最后的陈述中

returns 4 times factorialFinder(4-1)
它是返回 4

还是返回 20,因为它先乘以 5*4?

为了深入了解任何代码的工作原理,您可以打印应用程序运行位置的步骤

例如:

#include <iostream>
using namespace std;
int factorialFinder(int x) {
    cout << "f: " << x << endl;
    if (x==1) {
        cout << "return 1" << endl;
        return 1;
    }else{
        const int res = x*factorialFinder(x-1);
        cout << "return " << res << endl;
        return res;
    }
}
int main()
{
    cout << factorialFinder(5) << endl;
}

输出为:

f: 5
f: 4
f: 3
f: 2
f: 1
return 1
return 2
return 6
return 24
return 120
120

生成跟踪的一种方法是检测代码,添加跟踪输出语句。为此创建一些支持可能是个好主意。例如,

#include <iostream>
#include <string>
using namespace std;
auto operator*( int const n, string const& s )
    -> string
{
    string result;
    for( int i = 1; i <= n; ++i ) { result += s; }
    return result;
}
class Tracer
{
private:
    std::string callspec_;
    std::string result_;
    auto call_level()
        -> int&
    {
        static int the_level;
        return the_level;
    }
    static auto indent() -> string { return ".  "; }
public:
    template< class Value >
    auto result( Value v )
        -> Value
    {
        result_ = to_string( v );
        return v;
    }
    ~Tracer()
    {
        --call_level();
        clog << "<- " << call_level()*indent() << callspec_;
        if( not result_.empty() )
        {
            clog << " returns " << result_;
        }
        clog << endl;
    }
    Tracer( string funcname )
        : callspec_( move( funcname ) )
    {
        clog << "-> " << call_level()*indent() << callspec_ << endl;
        ++call_level();
    }
};
auto factorial( int const x )
    -> int
{
    Tracer trace( "factorial " + to_string( x ) );
    return trace.result( x == 1? 1 : x*factorial( x - 1 ) );
}
auto main() -> int
{
    cout << factorial( 5 ) << endl;
}

结果:

->阶乘 5-> . 阶乘 4-> . . 阶乘 3-> . . . 阶乘 2-> . . . . 阶乘 1<- . . . . 阶乘 1 返回 1<- . . . 阶乘 2 返回 2<- . . 阶乘 3 返回 6<- . 阶乘 4 返回 24<- 阶乘 5 返回 120120

但是,仅使用调试器逐步执行代码也可以以更少的工作量获得启发。