有15个数按由小到大的顺序存放在一个数组中,输入一个数,用折半查找法找出它是数组中的第几个元素的值。如果不在的话,就打印“没有找到”
在我的教材里看到的这个程序,怎么运行时,如果数组里有的数就正确呢? 当数组里没有这个数时运行就不正确了?就不能按照要求显示!这是怎么回事啊?请教下!谢谢各位
#define N 15
void main()
{ int i,num,top,bott,mid,loca,a[N],flag=1,sign=1;
char c;
printf("Enter data:\n");
scanf("%d",&a[0]);
i=1;
while(i<N)
{scanf("%d",&a[i]);
if(a[i]>=a[i-1])
i++;
else
printf("Enter the data again:");
}
printf("\n");
for(i=0;i<N;i++)
printf("%4d",a[i]);
printf("\n");
flag=1;
while(flag)
{printf("Input number to look for:");
scanf("%d",&num);
loca=0;
top=0;
bott=N-1;
if((num<a[0])||(num>a[N-1]))
loca=-1;
while((sign==1)&&(top<=bott))
{mid=(top+bott)/2;
if(num==a[mid])
{loca=mid;
printf("Find %d, its position is %d\n",num,loca+1);
sign=0;
}
else if(num<a[mid])
bott=mid-1;
else
top=mid+1;
}
if(sign==1||loca==-1)
printf("%d is not found.\n",num);
printf("Continue or not (Y/N)?");
scanf("%c",&c);
if(c=='N'||c=='n')
flag=0;
}
}
#define N 15
void main()
{ int i,num,top,bott,mid,loca,a[N],flag=1,sign=1;
char c;
printf("Enter data:\n");
scanf("%d",&a[0]);
i=1;
while(i<N)
{scanf("%d",&a[i]);
if(a[i]>=a[i-1])
i++;
else
printf("Enter the data again:");
}
printf("\n");
for(i=0;i<N;i++)
printf("%4d",a[i]);
printf("\n");
flag=1;
while(flag)
{printf("Input number to look for:");
scanf("%d",&num);
loca=0;
top=0;
bott=N-1;
if((num<a[0])||(num>a[N-1]))
loca=-1;
while((sign==1)&&(top<=bott))
{mid=(top+bott)/2;
if(num==a[mid])
{loca=mid;
printf("Find %d, its position is %d\n",num,loca+1);
sign=0;
}
else if(num<a[mid])
bott=mid-1;
else
top=mid+1;
}
if(sign==1||loca==-1)
printf("%d is not found.\n",num);
printf("Continue or not (Y/N)?");
scanf("%c",&c);
if(c=='N'||c=='n')
flag=0;
}
}
...全文
相关推荐
2.有15个数存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则输出“无此数”。以15个数用赋初值的方法在程序
2.有15个数存放在一个数组中,输入一个数,要求用折半查找法找出该数是数组中第几个元素的值。如果该数不在数组中,则输出“无此数”。以15个数用赋初值的方法在程序中给出。要找的数用scanf函数输入。
数组a中已存有互不相同的10个整数从键盘输入一个整数,找出与该值相同的数组元素下标。 (如果没找到,输出“没找到”).c
数组a中已存有互不相同的10个整数从键盘输入一个整数,找出与该值相同的数组元素下标。 (如果没找到,输出“没找到”).c
找出一个整型数组中的元素的最大值
c语言中找出一个整型数组中的元素的最大值。源码
顺序栈,压栈、弹栈、获得栈顶元素、统计栈中元素个数、打印栈中元素
顺序栈,利用一组地址连续的存数单元依次存放自栈底到栈顶的数据元素,同时附设指针top指示栈顶元素在顺序栈中的位置,压栈、弹栈、获得栈顶元素、统计栈中元素个数、打印栈中元素
从键盘上输入3个数,把最小数找出来
编一个程序,从键盘上输入3个数,把最小数找出来。 (试着使用两种以上方法)


