求指点———>功能完善:利用折半查找法求数组元素序数
1.题目要求:
有十个数由小到大顺序存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果不在该数组中,则输出“无此数”。
2.程序如下:
#include"stdio.h"
#define N 10
int main(void)
{
int a[N],i,low,high,mid,num,found;
low=0;
high=N-1;
found=0;
printf("Please enter data:");
for(i=0;i<N;i++)
scanf("%d",&a[i])
printf("Please enter a number to look for:");
scanf("%d",&num);
while(low<=high)
{
mid=(low+high)/2;
if(num==a[mid]) {found=1;break;}
else if(num>a[mid]) low=mid+1;
else high=mid-1;
}
if(found==1)
printf("Has found %d,its position is:%d\n",num,mid+1);
else printf("There is not %d in the data\n",num);
return 0;
}
期望功能:
当输入一个数后,不管该数在不在该数组中,在结果输出后紧接着输出“Continue or not(Y/N)",若输入"Y/y",则继续执行printf("Please enter a number to look for:");及之后的语句;若输入"N/n",则程序结束。
由于我还只学到数组这章,函数后面的都没学,希望大家能在我的知识范围内指点一下,最好能在我原程序上的基础上告诉我怎么实现这个功能,可附上代码,谢谢大家。
[解决办法]
#include"stdio.h"
#define N 10
int main(void)
{
int a[N],i,low,high,mid,num,found;
char choice;
printf("Please enter %d integers:\n", N);
for(i=0;i<N;i++)
scanf("%d",&a[i]);
getchar();
while (1) {/* 死循环,选择了n才退出 */
printf("Please enter a number to look for:");
scanf("%d",&num);
getchar();
/* 把初始化放在这里,每次都初始化一次 */
found = 0;
low = 0;
high = N-1;
while(low<=high)
{
mid=(low+high)/2;
if(num==a[mid]) {found=1;break;}
else if(num>a[mid]) low=mid+1;
else high=mid-1;
}
if(found==1)
printf("Has found %d,its position is:%d\n",num,mid+1);
else
printf("There is not %d in the data\n",num);
printf("Continue or Not(Y/N): ");
scanf("%c", &choice);
if (choice == 'N'
[解决办法]
choice == 'n')
break;
}
return 0;
}