如何计算递归程序的步骤
How would one count the steps of a recursive program
我知道我需要一个程序计数器,我需要跟踪每个递归调用或步骤,这在for循环中很容易做到,但对于递归程序来说很难。我一直纠结于如何计算所有递归步骤。到目前为止,这就是我所拥有的。我也想过让我的方法void
,但有了int
,我至少可以根据最后的步骤尝试return counter
,但它不起作用。
int fibRec( int x, int counter )
{
if (x == 0)
return 0;
else if (x == 1)
return 1;
else
{
counter++;
return fibRec((x - 1) + (x - 2), counter);
}
}
这在for循环中很容易做到,但对于递归程序来说很难做到
对不起,你错了——在C++中为递归程序添加计数器之类的东西是很琐碎的。
a) 请注意,不需要全局设置
b) 不需要额外的方法参数。
和往常一样,C++解决方案是创建一个类
作为类的一部分的非静态递归方法将始终具有this指针,从而访问类的任何部分,包括您可能需要的任何数量的添加计数器和报告或方法。
这里有一种可能的方法:
class FibRec
{
public:
FibRec() : counter(0) {
std::cout << "FibRec ctor " << counter << std::endl;
};
~FibRec() { // output final value with dtor
std::cout << "FibRec dtor " << counter << std::endl;
};
int exec( int x )
{
if (x == 0) return 0;
else if (x == 1) return 1;
else
{
counter++;
// dbg: std::cout << counter << " " << x << std::endl;
return (exec(x - 1) + exec(x - 2));
// note -- Fibonacci fix?
}
}
private:
int counter;
};
int t407(void)
{
FibRec f; // class instance
f.exec(5); // invoke recursive method
return(0);
}
注意:使用g++,ubuntu 15.10的默认堆栈大小为8M字节。这是大量的递归。
不幸的是,您的代码有一个错误——它"添加"并很快增长到溢出。当计数器为272261时,我的代码显示溢出。您需要修复代码。
我猜这段代码应该是fibonacci,它是两个中间值的和。不是你编码的。
你可能会通过更改你的代码来实现你想要的:
return fibRec((x - 1) + (x - 2), counter);
至:
return (fibRec(x - 1, counter) + fibRec(x - 2, counter));
祝你好运。
您需要将counter
作为引用传入:
int fibRec( int x, int &counter )
这样,传入的调用方的本地变量就会更新。此外,您可能需要考虑增加基本情况(0和1)的counter
,因为从技术上讲,它们也是步骤。
您可以将变量作为引用传递
void fibRec( int x, int &counter )
或者你可以声明一个全局变量计数器,就像下面的代码一样
int counter = 0;
int fibRec( int x )
{
if (x == 0)
return 0;
else if (x == 1)
return 1;
else
{
counter++;
return fibRec((x - 1) + (x - 2));
}
}
相关文章:
- 是否总是可以将使用递归编写的程序重写为不使用递归的程序C++,性能观点是什么?
- 递归程序的执行流程
- 递归程序获得勒让德多项式
- 当有 2 个或更多递归函数写入 togeather 时,程序如何执行?
- 递归导致程序崩溃,但 while 循环中的相同概念不是来自C++析构函数
- 这个简单的程序如何不表示递归?
- 执行递归函数时 C++ 应用程序崩溃
- 如何理解哪个递归函数程序需要
- 以下递归程序的最后一行是如何工作的
- 如何使用mongocxx c ++驱动程序递归生成Mongodb文档?
- C 程序.该程序应使用递归和循环
- 具有递归函数且不带全局变量的程序 - C++
- 输出中的特定递归反向程序问题
- 生成给定集合的子集(使用递归)的程序的执行涉及哪些步骤
- 如何计算递归程序的步骤
- 为什么GCC在这个递归Fibonacci代码中生成的程序比Clang更快
- 以嵌套或递归方式(即在处理程序内)调用 asio io_service poll() 或 poll_one() 是否有效
- C++回文创建者递归程序
- 当我在递归函数中调用 return 时,我的程序意外完成
- 递归在这个快速排序程序中是如何工作的