所以我在这里有一个程序,它应该做一个非常简单的工作,通过一个 100 个整数的数组来搜索一个特定的键。这个程序中的linearSearch
函数应该是递归的,所以我必须从它内部调用函数。该程序编译得很好,但由于某种原因0
,无论您输入什么搜索键,都只返回数组中的第一个元素。我没有看到什么?谢谢。
#include <iostream>
using namespace std;
int linearSearch(const int[], int, int);
int main()
{
const int arraySize = 100; //size of array
int a[arraySize]; //create array a
int searchKey; //value to locate in array a
for(int i = 0; i < arraySize; i++)
a[i] = 2 * i; //create data
cout << "Enter integer search key: ";
cin >> searchKey;
//attempt to locate search key in array a
int element = linearSearch(a, searchKey, arraySize);
//display results
if(element != -1)
cout << "Found value in element: " << element << endl;
else
cout << "Value not found" << endl;
system("pause");
}
//linearSearch Function ****Returns 0 as index all the time *************
int linearSearch(const int array[], int key, int sizeOfArray)
{
static int index = 0;
//if Out of range, return -1 (Value not found)
if(index >= sizeOfArray){return -1;}
//if array value = key, array index is returned
if(array[index] == key){return index;}
//if array value is not equal to key, add to index and call func again
if(array[index] != key)
{
index++;
linearSearch(array, key, sizeOfArray);
}
}
我通过声明index
as来采取正确的方法static
,对吗?
〜非常感谢,你们很快而且帮助很大。=)