我正在尝试实现一个线性搜索函数来搜索用户“输入”的特定数字,例如,用户想要搜索给定数组中的数字 3。该函数应返回索引值 2。但无论我输入什么输入,我的代码都会返回 6。我怀疑我的 main 函数有问题(也许当我使用 for 循环时,我的值固定为 6?)。有任何想法吗?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define numberOfElements 6
#define NOT_FOUND -1
int linearSearch (int *myArray, int key, int i);
int main (int argc, char *argv[]){
int i, key, myArray[] = {1, 2, 3, 4, 5, 6};
printf("Input: ");
for (i = 0; i < numberOfElements; i++){
printf("%d ", myArray[i]);
}
printf("\n");
printf("Please enter a number you wish to search for: ");
scanf("%d", &key);
linearSearch (myArray, key, i);
printf("The number %d is at index %d\n", key, i);
return 0;
}
int linearSearch (int *myArray, int key, int i) {
for (i = 0; i < numberOfElements; i++){
printf("Checking index %d\n", i);
if (myArray[i] == key){
printf("%d\n", i);
return i;
break;
}
printf("It's certainly not here!\n");
}
return NOT_FOUND;
}