【发布时间】: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 那么你应该使用无符号整数,而不是有符号整数。