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

Why is the line 12 is printed twice?

给出的问题

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

我的解决方案

#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,行 The total numbers done done to locate the value-- is getting printed twice.

只是因为你调用了两次二分查找函数。 一个在 if part 上,另一个在 else if part 上。

您也可以通过以下方式进行同样的操作

int temp = bi_search(n);
if (temp == -1)
    printf("Value not found\n");
else
    printf("Value found at position %d\n", temp);

您正在调用 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;
}

您的主要例程可能如下所示:

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

1) int main()(让编译器冷静)

2) int res = bi_search(n)(避免第二次 bi_search() 调用)