#include <stdio.h> int main() { int a[6]={2,6,8,9,10}; int left=0,right=5; int mid,i_number; scanf("%d",&i_number); while(left<=right) { mid=(left+right)/2; if(a[mid]<i_number) { left=mid+1; }else if (a[mid]>i_number) { right=mid+1; }else{ break; } }// for (int i = 4; i>=left; i--) { a[i+1]=a[i]; } a[left]=i_number; for(int i=0;i<6;i++) { printf("%d ",a[i]); } } 哪有问题
时间: 2024-04-08 19:30:49 浏览: 147
#include <stdio.h>
4星 · 用户满意度95%
你的代码存在一个小错误。在二分查找的 else if 分支中,将 `right=mid+1` 改为 `right=mid-1`,以确保在目标数小于中间数时,将 right 更新为 mid-1。
下面是修改后的代码:
```c
#include <stdio.h>
int main()
{
int a[6] = {2, 6, 8, 9, 10};
int left = 0, right = 5;
int mid, i_number;
scanf("%d", &i_number);
while (left <= right)
{
mid = (left + right) / 2;
if (a[mid] < i_number)
{
left = mid + 1;
}
else if (a[mid] > i_number)
{
right = mid - 1;
}
else
{
break;
}
}
for (int i = 4; i >= left; i--)
{
a[i + 1] = a[i];
}
a[left] = i_number;
for (int i = 0; i < 6; i++)
{
printf("%d ", a[i]);
}
return 0;
}
```
现在代码已经修正,可以正确地将整数插入到升序数组中,并输出结果。请注意,这段代码假设输入的数组已经是升序排列的。如果输入数字是 `7`,则输出结果为 `2 6 7 8 9 10`。
阅读全文