我在这里有点困惑。让我们看下面的代码:
bool testing(int i) {
if((i%2)==0) {
return true;
} else {
--i;
testing(i);
}
return false;
}
当我执行
testing(5)
时,我期望该函数返回true,因为在某个时候,5
将变为4
,因此成为4 % 2 == 0
,因此该函数将返回true
,但事实并非如此。怎么了?
最佳答案
递归的想法是当函数直接或间接调用时。
如果将代码中的函数修改为:
bool testing(int i){
// test if even, if so return true
if((i % 2) == 0){
return true;
// otherwise decrement and test again
}else{
// at this point the function calls itself with decremented argument
return testing(--i);
}
// I doubt that this case will be ever returned
// more likely your function will return "true" or run "forever" decrementing
return false;
}
为了避免无限循环,您需要一个基本情况,即终止条件,该条件可产生结果而无需递归。例如,如果
i
变得非常小或为负数,则返回false
。bool testing(int i){
// base case
if(i < 0) return false;
// rest of the function
if((i % 2) == 0){
return true;
}else{
return testing(--i);
}
}
更简洁一点,您最终有以下三种情况:
bool testing(int i){
// base case
if(i < 0) return false;
// test if even
if((i % 2) == 0) return true;
// recursion step
return testing(--i);
}
如需进一步阅读,请检查this
关于c++ - 在C++中的递归函数中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32215194/