當我運行這個程序並輸入一個值來搜索程序崩潰(exe
已停止工作,關閉程序)。一旦輸入值65的時候,我得到了數無限循環未發現輸入要搜索的值(-1退出):C++程序崩潰(數組和2指針binsearch函數)
下面是代碼:
#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;
}
你的問題是什麼? –
我的問題是爲什麼我的代碼失敗/崩潰? – user1787130
我建議你自己去研究一下崩潰。首先使用調試器或插入輸出語句來查找崩潰發生的位置。然後從那裏開始嘗試找出問題所在。 –