当前位置: 代码迷 >> C语言 >> 折半法查数,,两个错误,,大家帮我看看哪里错了
  详细解决方案

折半法查数,,两个错误,,大家帮我看看哪里错了

热度:283   发布时间:2005-02-25 18:56:00.0
折半法查数,,两个错误,,大家帮我看看哪里错了

int binsearch(int x,int v[],int n) { int low,high,mid; low=0; high=n-1; mid=(low+high)/2; while(low<=high) { if(x<v[mid]) high=mid-1; else if(x>v[mid]) low=mid+1; else return mid; } return -1;

main() { int y, a[10]={1,2,3,4,5,6,7,8,9,10}; y=binsearch(10,a,10); printf("%d",y); }

搜索更多相关的解决方案: int  low  high  mid  else  

----------------解决方案--------------------------------------------------------
没什么,在语法上少了个}而已。

int binsearch(int x,int v[],int n){
int low,high,mid;
        low=0;
        high=n-1;
        mid=(low+high)/2;
        while(low&lt;=high){
                if(x&lt;v[mid])            high=mid-1;
                else if(x&gt;v[mid])       low=mid+1;
                else                    return mid;
        }
        return -1;
}
main(){
int y, a[10]={1,2,3,4,5,6,7,8,9,10};
        y=binsearch(10,a,10);
        printf("%d",y);
}
----------------解决方案--------------------------------------------------------
不,mid=(low+high)/2应该放在while语句里面
----------------解决方案--------------------------------------------------------
那不是语法错误,不用管它
----------------解决方案--------------------------------------------------------
算法错误比语法更严重啊!
----------------解决方案--------------------------------------------------------

int binsearch(int x,int v[],int n) { int low,high,mid; low=0; high=n-1; mid=(low+high)/2; !!这句子放错了位置啦!!!把它册啦! while(low<=high) { mid=(low+high)/2; !!应放在这里!! if(x<v[mid]) high=mid-1; else if(x>v[mid]) low=mid+1; else return mid; } return -1; } !!加上一个"}"

main() { int y, a[10]={1,2,3,4,5,6,7,8,9,10}; y=binsearch(10,a,10); printf("%d",y); }

[此贴子已经被作者于2005-3-6 12:59:38编辑过]


----------------解决方案--------------------------------------------------------
  相关解决方案