Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C调试中的递归线性搜索_C_Linear Search - Fatal编程技术网

C调试中的递归线性搜索

C调试中的递归线性搜索,c,linear-search,C,Linear Search,问题:1 在这段代码中,如果我搜索一个不在数组中的数字,它应该显示未找到的值,但我不知道它没有显示该消息,而是每次它在元素-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 s

问题:1 在这段代码中,如果我搜索一个不在数组中的数字,它应该显示
未找到的值
,但我不知道它没有显示该消息,而是每次它在元素-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);

}

1) 主要问题是
if(size正如大家所说的,您有一个小错误,那就是,您应该编写
if(size==0)
而不是
if(size只要将if语句从
if(size
if)改为
if(SizeLook是学习调试器的一个很好的例子。使用调试器。它可以在您单步执行每条指令时显示变量的值。只需更改
size@stark0是数组的大小而不是位置。
size-1
是位置。如果要返回size\u t
更改为
int
e> -1
if(key == array[size-1]){
        return size-1;
return linearSearch(array, key, size-1);
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);
    }
}
element = linearSearch(a, searchKey, SIZE);