不好意思忘了,是有10个数,输入一个数,用折半法找出该数是第几个元素的值,如果不在则打印“无”。
#include "stdio.h"
#include "conio.h"
#define N 10
main()
{
int mid,top,bott,a[N],i,num,flag=1,sign=1,loca=0;
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");
}
for(i=0;i<N;i++)
printf("%4d",a[i]);
printf("\n");
while(flag)
{
printf("enter a number to look for:\n");
scanf("%d",&num);
top=0;
bott=N-1;
if((num<a[0])||(num>a[N-1]))
loca=1;
while((top<=bott)&&(sign==1))
{
mid=(top+bott)/2;
if(num==a[mid])
{
printf("find the number %d in NO.%d.\n",num,mid+1);
sign=0;
}
else if(num>a[mid])
top=mid+1;
else
bott=mid-1;
}
if(loca==1||sign==1)
printf("%d is not find!\n",num);
printf("do you want enter again:('y'or'n')\n");
scanf("%c",&c);
if(c=='N'||c=='n')
flag=0;
}
getch();
}
[此贴子已经被作者于2007-3-21 14:34:58编辑过]