Closed. This question needs details or clarity. It is not currently accepting answers. Learn more
想改进这个问题吗?添加细节并通过editing this post澄清问题。
两年前关闭。
#include <stdio.h>

int main() {
    int a[80], lo = 1, hi, i, mid, object, n;
    printf("enter the size of the array");
    scanf("%d", &n);
    printf("enter the elements in the array in ascending order");
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    printf("enter the element you want to find in the array");
    scanf("%d", &object);
    lo = 0;
    hi = n - 1;
    mid = (lo + hi) / 2;
    while (lo <= hi) {
        if (mid < object) {
            lo = mid + 1;
        }
        if (mid > object) {
            hi = mid - 1;
        }
        if (mid == object) {
            printf("the element %d is found at %d", object, mid);
            break;
        }
    }
}

最佳答案

代码被破坏:
mid不会在每次迭代时重新计算;
您应该比较数组元素a[mid]object而不是其索引mid
以下是更正版本:

#include <stdio.h>

int main(void) {
    int a[80], i, n, lo, hi, mid, object;

    printf("Enter the size of the array: ");
    if (scanf("%d", &n) != 1 || n < 0 || n > 80)
        return 1;
    printf("Enter the elements in the array in ascending order: ");
    for (i = 0; i < n; i++) {
        if (scanf("%d", &a[i]) != 1)
            return 1;
    }
    printf("Enter the element you want to find in the array: ");
    if (scanf("%d", &object) != 1)
        return 1;
    lo = 0;
    hi = n;
    while (lo < hi) {
        mid = lo + (hi - lo) / 2;
        if (a[mid] < object) {
            lo = mid + 1;
        } else
        if (a[mid] > object) {
            hi = mid;
        } else {
            printf("the element %d is found at %d\n", object, mid);
            break;
        }
    }
    return 0;
}

笔记:
检查scanf()中的返回值是否成功转换,避免在无效输入上出现未定义的行为。
n必须在080的范围内。
多余的测试被删除。
mid = lo + (hi - lo) / 2;mid = (lo + hi) / 2;好,因为它避免了lo + hi上的潜在算术溢出。当然,这是一个有争议的观点,因为n <= 80但它是一个很好的预防措施,总是使用更安全的建设。不安全(lo + hi) / 2是许多主流实现中的一个臭名昭著的错误,这种错误持续了几十年,直到足够大的数组显示出未定义的行为。

关于c - 我试图在C中实现二进制搜索,但显示运行时错误。我已经从互联网上获取了代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45904736/

10-12 15:02