在C++中跟踪递归阶乘函数
Tracing a recursive factorial function in C++?
做
点运动有困难,假设我有:
#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
但是,仅使用调试器逐步执行代码也可以以更少的工作量获得启发。
相关文章:
- 在 C++ 中的数组上使用阶乘函数
- 为什么我在C++阶乘函数中出现编译错误?
- 阶乘函数只返回C++中输入的答案
- 为什么我不能在非常量表达式上使用此模板阶乘函数?
- 返回阶乘C++的递归函数
- C++ 中是否有任何内置阶乘函数?
- 为什么叮当使我的简单阶乘函数过于复杂
- 3 函数加主函数 C 程序计算和显示阶乘
- 带有自定义数字的阶乘函数不起作用
- 阶乘函数不适用于大数
- 自定义阶乘函数未按预期工作
- 递归阶乘函数在"22!"上产生不正确的结果
- 为什么这个阶乘函数返回int而不是double
- 在C++中跟踪递归阶乘函数
- 带有值的递归阶乘错误返回语句,在函数中返回 'void' [-fallowive]
- 记忆化的递归阶乘函数
- 了解如何在c++中使用阶乘函数
- 为什么阶乘递归函数比普通阶乘函数效率低
- 有数据类型问题的c++阶乘函数
- 如何在c++中实现阶乘函数并进行正确的错误处理