int main() { int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; int k = 0; printf("请输入你需要查找的数字\n"); scanf("%d", &k); int sz = sizeof(arr) / sizeof(arr[0]); int left = 0;//左下标 int right = sz - 1;//右下标 while (left <= right) { int mid = (left + right) / 2;//中间元素下标;mid = left+(right-left)/2 if (arr[mid] < k) { left = mid + 1; } else if (arr[mid] > k) { right = mid - 1; } else { printf("找到了下标是:%d", mid); break; } if (left > right) printf("不存在该数字\n"); } return 0; }修改代码中的错误
时间: 2024-01-15 22:02:36 浏览: 73
cPP.zip_4 3 2 1
代码中并没有明显的错误,只有一处不规范之处,即缺少了 else 语句。当找到目标元素时应该及时退出循环,避免继续执行不必要的比较操作。修改后的代码如下:
```
int main() {
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int k = 0;
printf("请输入你需要查找的数字\n");
scanf("%d", &k);
int sz = sizeof(arr) / sizeof(arr[0]);
int left = 0;//左下标
int right = sz - 1;//右下标
while (left <= right) {
int mid = (left + right) / 2;//中间元素下标;mid = left+(right-left)/2
if (arr[mid] < k) {
left = mid + 1;
}
else if (arr[mid] > k) {
right = mid - 1;
}
else {
printf("找到了下标是:%d\n", mid);
break;
}
}
if (left > right)
printf("不存在该数字\n");
return 0;
}
```
阅读全文