问题:1 在这段代码中,如果我搜索一个不在数组中的数字,它应该显示Value not found
,但我不知道它没有显示该消息,而是每次显示时Found value in element -5
我都不知道它为什么会发生。
#include<stdio.h>
#define SIZE 100
size_t linearSearch(const int array[], int key, size_t size);
int main(void)
{
int a[SIZE];
size_t x;
int searchKey;
size_t element;
for(x=0; x<SIZE; ++x){
a[x] = 2*x;
}
for(x=0; x<SIZE; ++x){
if(x%10 == 0){
puts("");
}
printf("%5d", a[x]);
}
puts("\n\nEnter integer search key:");
scanf("%d", &searchKey);
// attempt to locate searchKey in array a
element = linearSearch(a, searchKey, SIZE);
// display results
if(element != -1){
printf("Found value in element %d", element);
}
else{
puts("Value not found");
}
}
size_t linearSearch(const int array[], int key, size_t size)
{
if(size<0){
return -1;
}
if(key == array[size-1]){
return size-1;
}
return linearSearch(array, key, size-1);
}
问题:2
我无法理解如何
size_t 线性搜索(const int array[], int key, size_t size)
功能特别适用于这些线
if(key == array[size-1]){
return size-1;
return linearSearch(array, key, size-1);