能不能帮我看看我这为啥不能运行啊。可以编译。就是显示停止工作
#include<stdio.h>int main()
{void find(int a[],int b,int high,int low);
int a={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,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)
printf("we have the %dst number is %d",mid,a);
if(b>a)
low=mid+1;
if(b<a)
high=mid-1;
}
printf("we dont have the number");
}
代码如上,就是二分法查数字,麻烦大家了
#include <stdio.h>
#include <stdlib.h>
int main()
{
void find(int a[],int b,int high,int low);
int a={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,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)
{
printf("we have the %dst number is %d",mid,a);
exit(0);
}
else if(b>a)
low=mid+1;
else if(b<a)
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,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)
low = mid + 1;
if(b < a)
high = mid - 1;
if(b == a)
break; // 找到数后中断循环
}
if(b == a)
{
printf("we have the %dst number is %d\n",mid,a);
}
else
printf("we dont have the number\n");
}
再次修改程序,如若不然,无论能不能找到数,printf("we dont have the number\n"); 都会输出一次
baige 发表于 2020-10-9 21:53
谢谢大佬 风过无痕1989 发表于 2020-10-9 22:27
只改了你的程序两处,程序中有注释:
谢谢大佬,
页:
[1]