c - 为什么第 12 行被打印了两次?

标签 c arrays runtime-error binary-search

给出的问题

以非递归方式实现二分查找算法。 将搜索数组保持为数字数组,在声明时初始化并保持全局。 该程序应该要求一个值来搜索,然后告诉它找到的位置。 如果未找到该值,程序应显示未找到。 * 此外,程序应显示为定位值所做的比较总数(或意识到未找到该值)

我的解决方案

#include<stdio.h>
int arr[]={1,3,4,6,8,9,10,15,17,21};
int bi_search(int n)
{
    int start=0,end=9,mid=0,count=0;
    while(start<=end)
    {
        count++;
        mid=(start+end)/2;
        if(n==arr[mid])
            {
                printf("\nThe total number of comparisons done to locate the value--%d\n",count);
                return mid;
            }
        else if(n<arr[mid])
            end=mid-1;
        else
            start=mid+1;
    }
    printf("\nThe total number of comparisons done to realize that the value was not found--%d\n",count);
    return-1;
}
main()
{
    int n=0,ch=0;
    do
    {
        printf("\nEnter the value you want to search for--\n");
        scanf("%d",&n);
        if(bi_search(n)==-1)
             printf("\nSORRY :( !! \nThe value was not found.");
        else
             printf("\nHurray :) !! \nThe value you entered found at %d position", bi_search(n)+1);
        printf("\nEnter:-\n\t1 to continue.\n\t2 to terminate.\n");
        scanf("%d",&ch);
    }while(ch==1);
    printf("\nThank You\n");
    return 0;
}

当我运行此代码时,在函数 bi_search(int n) 中,每当 arr[mid] 变得等于 n 时,行 为定位值而进行的比较总数-- 被打印两次。

最佳答案

您正在调用 bi_search 函数两次。一次是在 if 语句中,一次是在 printf 语句中。您应该只调用一次,并缓存该值。

main()
{
    int n=0,ch=0;
    do
    {
        printf("\nEnter the value you want to search for--\n");
        scanf("%d",&n);
        if(bi_search(n)==-1) // Calling it here
             printf("\nSORRY :( !! \nThe value was not found.");
        else
             printf("\nHurray :) !! \nThe value you entered found at %d position", bi_search(n)+1); // And here
        printf("\nEnter:-\n\t1 to continue.\n\t2 to terminate.\n");
        scanf("%d",&ch);
    }while(ch==1);
    printf("\nThank You\n");
    return 0;
}

关于c - 为什么第 12 行被打印了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28715916/

相关文章:

c - R_X86_64_32S 和 R_X86_64_64 重定位是什么意思?

c++ - 初始化一个复杂的对象。当我不这样做时出错?

c++ - 将字符串映射到 int CPP - 输出在执行期间挂起

php - Nginx + php5-fpm 不显示 php 错误但 cli 显示错误

c - 打印指向不带括号的矩阵的指针

c++ - x64 位的 C++/CLI DLL 和 Exe 应用程序崩溃

jQuery,无法让自定义验证消息正常工作

javascript - 尝试创建一个 for 循环来记录数组中的偶数

python - 按元素比较两个 NumPy 数组的相等性

cpu - 更改中断 vector 表