|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<stdio.h>
- #define M 10
- int main()
- {
- static int a[M]={-12,0,6,16,23,56,80,100,110,115};
- int n,low,mid,high,found;
- low=0;
- high=M-1;
- found=0;
- printf("Input a number to be searched:");
- do
- {
- scanf("%d",&n);
- }while(n<a[0] || n>a[M-1]);
-
- while (low <= high)
- {
- mid=(low+high)/2;
- if(n==a[mid])
- {
- found=1;
- break;
- }
- else if(n>a[mid])
- {
- low=mid+1;
- }
- else
- {
- high=mid-1;
- }
- }
- if(found==1)
- {
- printf("The index of %d is %d",n,mid);
- }
- else
- {
- printf("There is no %d",n);
- }
- return 0;
- }
复制代码
我这个程序并没有像小甲鱼视屏教程里讲的那样在scanf后面加getchar()也能运行,而且输入字母居然也行。求大佬解惑
鱼哥的视频好像是在2008年录的,现在的编译器比如说Devc++,你的输入指令是scanf("%d",&n);那么你输入的如果是字符的话n是不会被赋值的,n的默认值是0,在devc++中%d只能接受整形数据,其他的都不接收。如果在定义n时给出一个int n = 1;那么输入a的话运行结果就会是There is no 1,因为%d不接受字符a,所以它还是我们定义的默认值1,楼主你的程序是对的,这一点不用深究的。
|
|