有15个数按由小到大的顺序存放在一个数组中,输入一个数,用折半查找法找出它是数组中的第几个元素的值。如果不在的话,就打印“没有找到”

nothingiknow 2007-12-08 02:52:33
在我的教材里看到的这个程序,怎么运行时,如果数组里有的数就正确呢? 当数组里没有这个数时运行就不正确了?就不能按照要求显示!这是怎么回事啊?请教下!谢谢各位
#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;
}
}
...全文
2895 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
san_dan 2007-12-08
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <iostream.h> //下面用到了cin
#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);
sign=1; //我觉得这里要加上这条,要不然下面选Y时不能执行到正确结果
printf("Continue or not (Y/N)?");
cin>>c; //这里用scanf("%c",&c);起不到选择的效果.
if(c=='N' ¦ ¦c=='n')
flag=0;
}
}
nothingiknow 2007-12-08
  • 打赏
  • 举报
回复
谢谢哈
srq1625 2007-12-08
  • 打赏
  • 举报
回复
#include<stdio.h>//你注意到你的程序里其实没有文件头。

#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;
}
}
我运行了一下,好了。继续加油啊,o(∩_∩)o...

70,022

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧