在二进制搜索中,我有我在标题中写的警告:
#include <stdio.h>
int bins(int, int, int, int);/*this function do a binary search*/
int main()
{
int n, low, high, v[]={0,1,2,3,4,5,6,7,8,9,10};
low=0;high=11;
printf("please enter the num you want to findn:");
scanf("%d", &n);
printf("%d", bins(n, v, low, high));
return 0;
}
int bins(int n, int v[], int low, int high)
{
int mid;
if(low>high)
{
return -1;
}
mid=(high+low)/2;
if(v[mid]>n)
{
bins(n, v, low, high-mid);
}
if(v[mid]<n)
{
bins(n, v, low+mid, high);
}
return mid;
}
考虑到数组是有组织的。
我有一个警告"传递'bins'的参数 2 从指针生成整数而不进行强制转换"。
bins
定义的头部:
int bins(int n, int v[], int low, int high) { ...
与函数的原型不同:
int bins(int, int, int, int); /*this function do a binary search*/
在第二个参数定义中。
在前者中,第二个参数的类型是指向int
的指针。 在后者中,第二个参数的类型为int
。
存在不匹配。
更正函数原型处的第二个参数:
int bins(int, int[], int, int); /*this function do a binary search*/
|
Here
并且代码在没有警告的情况下编译。
旁注:
bins()
中的算法似乎有问题。无论n
是什么,它都会返回mid = 5
,因为mid
只由(high+low) / 2
分配。