有15个数按由大到小顺序存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。

2016-06-17 11:43:04  分类: c程序设计第四版谭浩强课后答案  参与:

 有15个数按由大到小顺序存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则输出“无此数”。

以下是此题的【c源代码】,需要【c++源代码】请点击进入

#include <stdio.h>
#define  N 15
int main()
{ int i,number,top,bott,mid,loca,a[N],flag=1,sign;
  char c;
  printf("enter data:\n");
  scanf("%d",&a[0]);
  i=1;
  while(i<N)
   {scanf("%d",&a[i]);
    if (a[i]>=a[i-1])
      i++;
    else
      printf("enter this data again:\n");
   }
  printf("\n");
  for (i=0;i<N;i++)
    printf("%5d",a[i]);
  printf("\n");
  while(flag)
    {printf("input number to look for:");
     scanf("%d",&number);
     sign=0;
     top=0;            //top是查找区间的起始位置
     bott=N-1;         //bott是查找区间的最末位置
     if ((number<a[0])||(number>a[N-1]))  //要查的数不在查找区间内
       loca=-1;        // 表示找不到
     while ((!sign) && (top<=bott))
       {mid=(bott+top)/2;
        if (number==a[mid])
         {loca=mid;
          printf("Has found %d, its position is %d\n",number,loca+1);
    sign=1;
         }
        else if (number<a[mid])
         bott=mid-1;
        else
        top=mid+1;
       }
     if(!sign||loca==-1)
       printf("cannot find %d.\n",number);;
  printf("continu or not(Y/N)?");
     scanf(" %c",&c);
     if (c=='N'||c=='n')
    flag=0;
    }
  return 0;
   }

来源:c程序设计第四版谭浩强课后答案

本文链接:http://www.wb98.com/c/post/tanhaoqiang_6.9.html

本站文章搜索:

<< 上一篇下一篇 >>

搜索

网站分类

Tags列表

赞助商链接