You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何这段C++代码无法打印binarySearch函数的返回值?

问题排查与修复

核心问题:死循环导致函数无法返回

你的binarySearch函数里,mid变量仅在函数开头计算一次,循环过程中从未更新mid的值。当arr[mid]不等于目标值时,你修改了l或r,但mid始终保持初始值,循环条件l<=r会一直成立,程序陷入死循环,永远到不了返回语句,自然无法打印返回值。

修复后的代码

#include<bits/stdc++.h>
using namespace std;

int binarySearch(int [], int, int, int);

int main()
{
    int n, ar[50], givensum;
    cout << "Enter the size of the array: ";
    cin >> n;
    for(int i = 0; i<n; i++)
    {
        cout << "ar[" << i << "] = ";
        cin >> ar[i];
    }
    sort(ar, ar+n); // 二分查找必须依赖有序数组,添加排序步骤
    cout << "Enter the given sum: ";
    cin >> givensum;
    cout << "The closest sum possible is: " << binarySearch(ar, 0, n-1, givensum) << endl;  
}

int binarySearch(int arr[], int l, int r, int key)
{
    while(l<=r)
    {
        int mid = l+(r-l)/2; // 将mid的计算移到循环内部,每次迭代更新
        if(arr[mid]==key)
            return arr[mid]+1;
        else if(arr[mid] > key)
            r = mid-1;
        else
            l = mid+1;
    }
    // 循环结束后,根据l和r判断最接近key的元素
    if (r < 0) return arr[l];
    if (l >= r+1) return arr[r];
    return abs(arr[l]-key) < abs(arr[r]-key) ? arr[l] : arr[r];
}

额外关键提醒

  • 二分查找的核心前提是数组必须有序,原代码缺少排序步骤,即使修复死循环,查找结果也会完全错误,因此在调用binarySearch前必须添加排序逻辑。
  • 原函数的返回逻辑不符合“找最接近的和”的需求,修复后的代码补充了循环结束后判断最接近元素的逻辑,可根据实际面试需求进一步调整。

内容的提问来源于stack exchange,提问作者HellsapwnXerxes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:35:26