无论我搜索什么值,程序都会在文件中找不到它。我无法弄清楚我的代码有什么问题。二进制搜索功能故障
int main()
{
int array1[MAX_NUMBER];
int length;
int number;
int location;
input (array1, MAX_NUMBER, length);
cout<<"Please enter a number to search for:"<<endl;
cin>>number;
location=search(array1, length, number);
if (location!=-1)
{
cout<<"The number "<<number<<" was found in the "<<location<<" position."<<endl;
}
else
{
cout<<"The number "<<number<<" was not found in the file."<<endl;
}
return 0;
}
void input(int a[], int size, int& number_used)
{
ifstream infile;
int input;
infile.open("numbers.txt");
if (infile.fail())
{
cout<<"Input file opening failed."<<endl;
exit(1);
}
int i;
for (i=0; i<=size; i++)
{
while (infile>>input)
{
a[i]=input;
cout<<a[i]<<endl;
}
}
number_used=i;
}
int search(const int a[], int number_used, int search_value)
{
int start=1;
int end=number_used;
int key=search_value;
while (start<=end)
{
int mid=((start+end)/2);
if (a[mid]==key)
{
return mid;
}
if (a[mid]>key)
{
end=mid-1;
}
else
{
start=mid+1;
}
}
return -1;
}
我的问题在主代码或搜索功能?
输入文件:
1
5
6
7
11
19
21
23
33
54
78
97
例如,键入19,则输出为 “数19在该文件中未找到”。
您的问题是,您没有使用调试器 – 2013-04-28 16:56:49