C++程序进入无休止的输入周期
这是一个简单的二进制搜索程序,但是由于某种原因,该程序在询问用户的密钥值后就不会继续前进。起初,我认为这是我的编译器的问题,但是无论我在哪里粘贴代码,它仍然会发生,而且我不知道为什么。
#include <iostream>
using namespace std;
int binary(int arr[], int n, int k){
int s = 0;
int e = n;
int mid = (s+e)/2;
while(s<=e){
if(k==arr[mid]){
return mid;
}
else if(k>arr[mid]){
s = mid+1;
}
else if(k<arr[mid]){
e = mid-1;
}
}
return -1;
}
int main(){
int i, n, key;
cin>>n;
int a[n];
for(i=0;i<n;i++){
cin>>a[i];
}
cout<<"Enter key:"<<endl;
cin>>key;
cout<< binary(a, n, key);
}
代码不用k
继续前进,而是什么都不做。
This is a simple binary search program, but for some reason, the program just doesn't move on after asking for the value of the key from the user. At first, I thought it is an issue with my compiler, but it still happens wherever I paste the code, and I don't know why.
#include <iostream>
using namespace std;
int binary(int arr[], int n, int k){
int s = 0;
int e = n;
int mid = (s+e)/2;
while(s<=e){
if(k==arr[mid]){
return mid;
}
else if(k>arr[mid]){
s = mid+1;
}
else if(k<arr[mid]){
e = mid-1;
}
}
return -1;
}
int main(){
int i, n, key;
cin>>n;
int a[n];
for(i=0;i<n;i++){
cin>>a[i];
}
cout<<"Enter key:"<<endl;
cin>>key;
cout<< binary(a, n, key);
}
Instead of moving on after k
, the code just does nothing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码在“二进制”函数中循环
尝试以查看
学习使用调试器来浏览代码
you code is looping in the 'binary ' function
try this to see
learn to use your debugger to step through the code
中间元素在二进制搜索中的循环内发现,因为搜索间隔在每次迭代中都减少到一半。
您的中间没有改变,这就是为什么该程序没有终止的原因。
因此,校正后的最终代码是:
The middle element is found inside the loop in binary search because the search interval is reduced to half in every iteration.
Your mid is not changing that is why the program is not terminating.
So final code after correction is: