|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目要求:有15个已经排序号的数存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则输出无此数。
变量说明:top,bott为查找区间两端点的下标;loca为查找成功与否的开关变量。
这段代码哪里错了,为什么输出异常?
- #include<stdio.h>
- int main()
- {
- int N,number;
- int top,bott,min,loca;
- int a[15] = {-3,-1,0,1,2,4,6,7,8,9,12,19,21,23,50};
- printf("Input the number to be found:");
- scanf("%d",&number);
- loca = 0;
- top = 0;
- bott = N-1;
- if((number < a[0]) || (number > a[N-1]))
- {
- loca = -1;
- }
- while((loca == 0)&&(top <= bott))
- {
- min = (top + bott)/2;
- if(number == a[min])
- {
- loca = min;
- printf("The serial number is %d. \n",loca+1);
- }
- else if(number < a[min])
- {
- bott = min - 1;
- }
- else
- {
- top = min + 1;
- }
- }
- if(top > bott)
- {
- printf("%d isn't in tabel\n",number);
- }
- }
复制代码
|
|