XP下用WINTC写的二分法。
#include"stdio.h"
#include"conio.h"
#define N 5
main()
{
int array[N];
int i,number,top,bott,mid,loca,flag=1,sign;
char c;
printf("enter data:\12");
i=0;
while(i<N)
{
scanf("%d",&array[i]);
if(array[i]<array[i-1]&&i>0)
{
printf("enter this data again:\12");
continue;
}
i++;
}
printf("\12");
while(flag)
{
printf("input number to look for: ");
scanf("%d",&number);
sign=0;
top=0;
bott=N-1;
if((number<array[0])&&(number>array[N-1]))
{
loca=-1;
}
while(!sign&&top<=bott)
{
mid=(top+bott)/2;
if(number==array[mid])
{
loca=mid;
printf("Has found %d,its position is %d\12",number,loca+1);
sign=1;
}
else if(number<array[mid])
{
bott=mid-1;
}
else
{
top=mid+1;
}
}
if(!sign||(loca==-1))
{
printf("can not found %d.\12",number);
}
printf("continue or not(Y/N)? \12");
scanf("%c",&c);
if(c=='N'||c=='n')
{
flag=0;
}
}
getch();
}
这是我在XP下用WINTC写的。。Y/N那块不问我。。直接就跳过了。。。
[解决办法]
printf("continue or not(Y/N)? \12"); rewind(stdin); //清空输入缓冲区中留下的回车字符 scanf("%c",&c);