更新时间2019-03-24 14:06:02
#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: ");
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: ");
}
printf(" ");
for (i=0;i<N;i++)
printf("%5d",a[i]);
printf(" ");
while(flag) //先进行总体大循环看你是要找一个数还是N个数
{
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 ",number,loca+1);
sign=1; //如果执行到本循环将会跳出,意味着找到此数
}
else if (number<a[mid]) //else if only the first condition is not met.
bott=mid-1;
else
top=mid+1;
}
if(!sign||loca==-1)
printf("cannot find %d. ",number);;
printf("continu or not(Y/N)?");
scanf(" %c",&c); //这里%c前面有空格和没有空格差距真的好大啊为啥啊????
if (c=='N'||c=='n')
flag=0;
}
return 0;
}
scanf(" %c",&c)和scanf("%c",&c)
主要是有回车的情况,因为普通的"%c"是会接收空格的
而若是“ %c",就会忽略空格了