我正在编写一个程序,该程序通过递归对用户输入的整数使用二进制搜索,其中0是最后输入的整数。我假设用户将按递增顺序输入它们,并且他们输入的整数不能超过10个。我已经开始使用它了,但是它总是返回所搜索的数字不在序列中。例:

Numbers entered: 1 2 3 4 5 6 0
Number to search for: 9
9 is in the series


我想这与不知道数组的大小有关,除了最大数组为10之外,但我不想询问用户想要的元素数量。我该如何解决?

#include <stdio.h>

int find_m(int a[], int i, int m)

{
    int mid;

    if (first>last) {
        return -1;
    }
    mid=(first+last)/2;
    if (a[mid]>m) {
        find_m(a, first, mid-1, m);
    }
    else if (a[mid]<m) {
        find_m(a, first, mid+1, m);
    }
    else {
        return mid;
    }

}


int main()

{
    int a[10], i, m, first, mid, last, found;

    for (i=0; i<10; i++) {
        printf ("Please enter integers (no more than 10 numbers) in increasing order with a 0 as the last number\n");
        scanf ("%d", &a[i]);
        if (a[i]==0) {
            break;
        }
    }

    printf ("Now enter a number you would like to find in the series\n");
    scanf ("%d", m);

    found=find_m(a, m, 0, i-1);

    if (found==1) {
        printf ("%d is not in the series\n", m);
    }
    else {
        printf ("%d is in the series\n", m);
    }

    return 0;

}

最佳答案

if (a[mid]>m) {
    find_m(a, first, mid-1, m);
}
else if (a[mid]<m) {
    find_m(a, first, mid+1, m);
}
else {
    return mid;
}


在上面的代码中,您只返回了if / else if / else块的3个可能分支中的1个值,然后函数结束了。因此,对于其他2个对象,您将获得未定义的行为。您需要return从对find_m()的调用中获得的结果,尽管从外观上看,found最终成为该数组中的位置。值不只是1。

10-07 19:10
查看更多