-4

问题: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);
4

3 回答 3

2

正如大家所说,你有一个小错误,就是你应该写if(size==0)if(size<0).

让我解释一下linearSearch()函数递归发生了什么

size_t linearSearch(const int array[], int key, size_t size)
{
    if(size == 0){
        return -1;
    }
    else
        if(key == array[size-1]){
            return size-1;
    }
    else{
        return linearSearch(array, key, size-1);
    }
}

假设您将输入198作为搜索键。当你linearSearch()通过语句调用函数时

element = linearSearch(a, searchKey, SIZE);

您将引用array[], searchKey 198, and Size 100作为参数传递。

在 linearSearch 函数中,首先 if 语句if(size==0)检查大小是否等于零,如果不是,则 else if 语句运行。

在 else if 语句If(198 == array[100-1])条件被检查。我们看到198存在于array[99]所以 else if 条件为真,因此 linearSearch 函数返回 99 作为结果。

现在让我们看看如果输入55不在数组列表中会发生什么。if(size==0) 不正确,因此程序将跳过它并转到下一条语句。 if(55 == array[100-1]将被检查为不正确,然后linearSearch(array, 55, 100-1)将被调用。将再次if(55==array[99-1])被检查。在某个点大小将变为 0。第一if(size==0)条语句将执行。

于 2016-10-15T13:06:58.717 回答
2

1)主要问题是if(size<0){。条件表达式将始终为假。因为 size_t 是无符号整数。因此,它返回一个随机位置,其中找到的值(这是未定义的行为)偶然变成一个大数字(例如 -5 是 4294967291 无符号)而没有结束(未找到)。

if(size<0){应该if(size==0){

2) 如果 key 匹配最后一个元素,则返回其位置。如果没有,请使用较短的一种尺寸重复。如果大小为零,则找不到密钥。

于 2016-10-04T03:22:05.687 回答
1

只需将 if 语句从更改if(size<0)if(size==0)您的代码即可。

于 2016-10-15T13:19:33.717 回答