【问题标题】:Why is my output wrong in this recursive function?为什么我的输出在这个递归函数中是错误的?
【发布时间】:2018-10-06 20:18:45
【问题描述】:

该函数只需要使用 (1+) 或 (2*) 返回从数字 x 到数字 y 的最小路径。例如,从 8 到 19,最小通行证是“3” 因为 (8*2+1+1+1=19),现在我的代码输出的是不同的数字而不是 3,我的问题是什么?

#include <stdio.h>
int f(int x, int y){

  if(x==y) 
    return 0;
  if(x>y)
    return -1;
  if(2*x < y){
    int max=f(2*x, y);
    return max+1;
  }
  else if(x+1<y){
    int max=f(x+1,y);
    return max+1;
  }
}

int main()
  {
    int idx=f(8,19);
    printf("%d", idx);

    return 0;
  }

【问题讨论】:

  • 这看起来像是调试器的工作!
  • 当我运行它时它会打印 22。请确保您发布了正确的minimal reproducible example
  • 请启用所有编译器警告,例如warning C4715: 'f': not all control paths return a value
  • 当 x = 18 时,没有一个 if 测试为真
  • @sam0101 那么你应该使用无符号整数,而不是有符号整数。

标签: c function recursion


【解决方案1】:

这里有两个问题。

1.当x 变为小于y 1 时,将不满足 if 条件,并且您不会返回任何未定义的行为。

因此替换

else if(x+1<y){

else {

2.你不应该在if(2*x &lt; y) 的情况下添加1+max 以获得正确的结果,因为你只想计算+1 完成的数量。

因此改变

int max=f(2*x, y); return max+1;

int max=f(2*x, y); return max;

添加完你所有的代码就变成了。

int f(int x, int y){

  if(x==y)
    return 0;
  if(x>y)
    return -1;
  if(2*x < y){
    int max=f(2*x, y);
    return max;
  }
  else {
    int max=f(x+1,y);
    return max+1;
  }
}

【讨论】:

  • 警告 C4715:'f':并非所有控制路径都返回值
  • return -1放在函数末尾,去掉if(x&gt;y)
  • @jwdonahue 是的!谢谢。
  • @jwdonahue 我认为最后不需要return -1
  • 我的编译器说你的代码没有在所有路径上都返回一个值。放置return -1' at the end, is the catch-all "we got here, something is very wrong statement". That would also include the x>y`场景。
【解决方案2】:

在这种情况下,您应该考虑一下您的函数将如何处理其变量。当它得到最后一次迭代时:

...
else if( x+1 < y ) {
    int max = f( x+1, y );
    return x+1;
}
...

这里的基兰是对的。使用 x = 8 和 y = 19 (如上所述),您会想起 x = 18 的函数,该函数将返回 undefined ,因为您的任何一个 if 都不会匹配。

一个可能的解决方案是:

int f( int x, int y ) {

    if( x < y ) {

        if( x * 2 < y ) return f( x * 2, y );
        else if( x + 1 <= y ) return 1 + f( x + 1, y );

    } else if( x == y ) return 0;
    else return -1;

}

【讨论】:

  • 我喜欢!最后处理最不可能的极端情况,所有控制流路径都返回有意义的东西。我认为 x 和 y 应该是无符号的。无论哪种方式,都应该为 2*x 溢出添加检查。
猜你喜欢
  • 2022-01-15
  • 1970-01-01
  • 2018-09-03
  • 2010-10-23
  • 1970-01-01
  • 2019-10-29
  • 2020-10-24
相关资源
最近更新 更多