我有一个关于迭代函数和递归函数的问题。我有一个迭代函数,我必须把它转换成递归函数。你能给我一些关于代码的建议吗?非常感谢
该代码使用递归来确定数据点数组是否对应于凹函数。
以下是迭代版本的代码:
bool isConcave(double a[], int n)
{
int slope = 1;
bool concave = true;
for (int i = 1; i < n && concave; i++)
{
double delta = a[i] - a[i-1];
if (slope > 0)
{
if (delta < 0)
slope = -1;
}
else if (delta > 0)
concave = false; // slope == -1 and delta > 0
}
return concave;
}并且,这是我的递归版本的代码,它不能工作:
bool isConcave_r(double a[], int n, int& slope)
{
//Implement this function using recursion
double delta = a[n] - a[n-1];
bool concave = true;
if (n == 0)
return false;
if (slope > 0)
{
if (delta < 0)
{
slope = -1;
}
else
concave = true;
}else
return 0;
//dummy return statement
return isConcave_r(a, n, slope);
}发布于 2013-10-15 18:47:04
不需要以最好/最干净的方式,但您可以替换任何循环
for (int i = 0; i != N; ++i) {
body(i, localVars);
}通过
void body_rec(int N, int i, LocalVars& localVars)
{
if (i == N) return;
body(i, localvars);
body_rec(N, i + 1, localVars);
}或
int body_rec(int N, int i, LocalVars& localVars)
{
if (i == N) return localVars.res; // or any correct value
body(i, localvars);
if (localVars.end) { // break the "loop", and so stop the recursion.
return localVars.res; // or any correct value
}
return body_rec(N, i + 1, localVars);
}因此,在本例中,您忘记了将slope传递到递归中。
编辑
完整的解决方案:
bool isConcave_r(int N, int i, double a[], int slope)
{
if (i >= N) return true;
const double delta = a[i] - a[i-1];
if (slope > 0) {
if (delta < 0) {
slope = -1;
}
}
else if (delta > 0) {
return false;
}
return isConcave_r(N, i + 1, a, slope);
}
bool isConcave(double a[], int n)
{
int i = 1;
int slope = 1;
return isConcave_r(n, i, a, slope);
}还请注意,名称似乎是“不正确的”,你不检查“曲线”是不是凹的,我认为delta == 0应该是具体的……
发布于 2013-10-15 18:57:52
在程序的迭代版本中,计算从1移动到n-1,但在递归版本中,计算从n-1移动到1。因此,不使用尾递归,而使用头递归。斜率应该是静态变量。因此,将slope声明为静态变量。看起来不错。
https://stackoverflow.com/questions/19379137
复制相似问题