|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
int main()
{ void find(int a[],int b,int high,int low);
int a[15]={15,16,17,18,19,20,21,22,23,24,25,26,27,28,29};
int b,high=14,low=0;
scanf("%d",&b);
find(a[14],b,high,low);
}
void find(int a[],int b,int high,int low)
{
while(low<=high)
{ int mid;
mid=(high-low)/2+low;
if(b==a[mid])
printf("we have the %dst number is %d",mid,a[mid]);
if(b>a[mid])
low=mid+1;
if(b<a[mid])
high=mid-1;
}
printf("we dont have the number");
}
代码如上,就是二分法查数字,麻烦大家了
本帖最后由 风过无痕1989 于 2020-10-9 22:56 编辑
只改了你的程序两处,程序中有注释:
#include<stdio.h>
int main()
{
void find(int a[],int b,int high,int low);
int a[15] = {15,16,17,18,19,20,21,22,23,24,25,26,27,28,29};
int b,high = 14,low = 0;
printf("请输入要寻找的数:");
scanf("%d",&b);
find(a,b,high,low); // 用数组名作为函数的实参
}
void find(int a[],int b,int high,int low)
{
int mid;
while(low <= high)
{
mid = (high - low) / 2 + low;
if(b > a[mid])
low = mid + 1;
if(b < a[mid])
high = mid - 1;
if(b == a[mid])
break; // 找到数后中断循环
}
if(b == a[mid])
{
printf("we have the %dst number is %d\n",mid,a[mid]);
}
else
printf("we dont have the number\n");
}
再次修改程序,如若不然,无论能不能找到数,printf("we dont have the number\n"); 都会输出一次
|
|