当我运行此程序并输入一个值来搜索程序崩溃时(exe
已停止工作,关闭程序)。一旦输入值65,我得到一个无限循环的数字未找到输入要搜索的值(-1退出):
以下是代码:
#include <iostream>
using namespace std;
void Search(int[], int * , int * );
int main()
{
int i,KEY,num, array[] = {98,87,76,65,54};
for(i=0;i<5;i++)
cout << array[i] << " ";
Search(array, &KEY, &num);
cout << endl;
system("pause");
return 0;
}
void Search(int arr[5], int * current, int * numel)
{
int low, high,search,N;
cout << "\nWhat Number would you like to search for? (-1 to quit) : ";
cin >> search;
while(search!=-1)
{
low=0;
high=N-1;
while(low<=high)
{
*current=(low+high)/2;
if (search > arr[*current])
low=*current+1;
else if(search<arr[*current])
high=*current-1;
else
break;
}
if(arr[*current]==search)
cout << "Number found at index " << *current << endl;
else
cout << "Number not found." << endl;
cout << "Enter a value to search (-1 to quit) :";
}
return;
}
答案 0 :(得分:1)
首先,如果所寻求的号码不在数组中,那么Search
中的主循环就没有办法了。
然后您在high
被赋予任何价值之前使用{{1}}。
可能还有其他问题。你是如何在开发它时测试它的?
答案 1 :(得分:0)
N
未初始化,所以谁知道这句话:
high=N-1;
会吗?