由于评论,输入未终止

时间:2014-03-22 10:46:19

标签: c++ scanf

此cpp代码未终止。我已经通过各种输入尝试了代码,但这不是终止。我认为第52行有一个错误,当我评论52行而不是代码工作正常。

#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
// binary search for larger elements
using namespace std;
vector <int > q;


// bsearch value uses hte 


#define bvector q // just define these values to use them in your functin
#define VALUE(x) bvector[x]

int b_search(int value){
int low=0,high=bvector.size(),mid;
    mid=(low+high)/2;
    cout << "In the bsearch";
    while(low<high)
    {
            if(VALUE(mid)==value)
                    return mid;
            else if(VALUE(mid)>value)//                      
                    high=mid;
            else if(VALUE(mid)<value)        
                   low=mid+1; 
    }

    if(VALUE(low)>value)
            return low;
    return -1;                
}

int main(){
int i;

    for(scanf("%d",&i);i;scanf("%d",&i))
            q.push_back(i); // this is for taking input in the vectot

sort(q.begin(),q.end());                

    for(i=0;i<q.size();i++)
            printf("%d ",q[i]);// for printing the sorted

            int j;
            printf("Enter the elements you want to search");

            int x;
            scanf("%d",&x);
 // BUG is present in this lines
            cout <<"This is the end of scanf";// if this line is commented then the 54th line is not reached

            j=b_search(x);
          printf("%d ",j);
return 0;
 }

1 个答案:

答案 0 :(得分:2)

声明:mid =(低+高)/ 2;有点错位。它应该在while循环中。 这可能是导致无限循环的原因。