C++ 为什么我的递归函数没有返回正确的值?
我正在实现一个二进制搜索,代码如下,但是,它没有打印出正确的答案,而是在函数体中打印出正确的答案,所以这让我很困惑C++ 为什么我的递归函数没有返回正确的值?,c++,algorithm,recursion,C++,Algorithm,Recursion,我正在实现一个二进制搜索,代码如下,但是,它没有打印出正确的答案,而是在函数体中打印出正确的答案,所以这让我很困惑 #include <iostream> using namespace std; int research(int a[], int target, int lowIndex, int highIndex) { int finalIndex; cout << lowIndex << " " << highIndex
#include <iostream>
using namespace std;
int research(int a[], int target, int lowIndex, int highIndex)
{
int finalIndex;
cout << lowIndex << " " << highIndex << endl;
int midIndex = (lowIndex + highIndex) / 2;
if (a[midIndex] == target)
{
finalIndex = midIndex;
cout << "The final index is: " << finalIndex << endl;
}
else
{
if (a[midIndex] < target)
{
research(a, target, midIndex + 1, highIndex);
}
else
{
research(a, target, lowIndex, midIndex - 1);
}
}
return finalIndex;
}
int main()
{
int* array = new int[1000];
for (int i = 0; i < 1000; i++)
{
array[i] = i + 1;
}
cout << research(array, 234, 0, 999) << endl;
return 0;
}
该行:
cout << "The final index is: " << finalIndex << endl;
打印出正确的最终索引,但行
cout << research(array, 234, 0, 999) << endl;
不会,而是打印出随机数。有人知道这里出了什么问题吗?谢谢大家! 实际将finalIndex设置为任意值的唯一时间是当[midIndex]==目标时,因此当您递归时,返回的是未初始化变量的值 finalIndex变量不在函数调用之间共享-每个调用使用自己的变量 您需要使用递归调用的返回值:
if (a[midIndex] < target)
{
finalIndex = research(a, target, midIndex + 1, highIndex);
}
else
{
finalIndex = research(a, target, lowIndex, midIndex - 1);
}
if和else块中缺少返回语句。您最需要修改基本的编程概念。特别是,编程不是魔术,编译器不是一个读心术,调用函数不会自动插入返回语句C++不是表达式语言。也许您想将递归调用的返回值分配给finalIndex;更好的是,把它们还回去。哦!我完全忘了!非常感谢你!