题目要求在数组18 , 26 , 39 , 41 , 52 , 66 , 74 , 86 , 91 , 97中查找39,小明编写程序如下,请问该程序存在几处错误?并改正。
输入样例
10
18 26 39 41 52 66 74 86 91 97
39
输出样例
2
心血来潮,出一道改错题\ ( ^ o ^ ) /
错误代码:
#include <iostream>
using namespace std;
int main() {
int n, a[105], x, left, right, mid, i, ans = -1;
cin >> n;
for (i = 0; i < n; i++) cin >> a[ i ];
left = 0;
right = n;
while (left >= right) {
mid = (left + right) / 2;
if (a[mid] = x) {
ans = mid;
} else if( a[mid] > x){
right = mid + 1;
} else {
left = mid + 1;
}
}
cout << ans;
return 0;
}
仔细一看,嗯?第八九行有亿点点问题
正确代码:
#include <iostream>
using namespace std;
int main(){
int n,a[105],x,left,right,mid,i,ans;
cin>>n;
for (int i = 0; i < n; i++)cin>>a[i];
cin>>x;
left=0;
right = n-1;//改了这里(n——n-1)
while(1){//改了这里(left >= right——1)
mid=(left+right)/2;
if(a[mid]==x){
ans=mid;
break;
}else if(a[mid]>x){
right = mid - 1;
}else{
left = mid+1;
}
}
cout<<ans;
return 0;
}