0

当我运行这个程序并输入一个值来搜索程序崩溃时(exe已停止工作,关闭程序)。一旦输入值 65,我得到一个 Number not found 无限循环输入要搜索的值(-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;
}
4

2 回答 2

1

Search对于初学者来说,如果寻找的数字不在数组中,则无法退出主循环。

然后你high在它被赋予任何价值之前使用它。

可能还有其他问题。在开发过程中你是如何测试它的?

于 2012-10-31T00:41:27.987 回答
0

N没有初始化,所以谁知道这个语句是什么:

high=N-1;

会做?

于 2012-10-31T00:40:49.197 回答