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

C语言equilibrium函数返回-1是否为笔误?求技术解析

为什么这段寻找平衡索引的C语言函数会返回-1?

Hey there! Let's break down this code and why returning -1 isn't a typo at all—it's intentional, correct behavior for a valid edge case.

First, let's clarify what this function does: it's searching for an equilibrium index in an array. An equilibrium index is a position where the sum of all elements to the left of the index equals the sum of all elements to the right.

Here's the code for reference:

int equilibrium(int array[], int size) { 
    int sum = 0; 
    int left_sum = 0; 
    int i; 
    for (i = 0; i < size; i++) { 
        sum += array[i]; 
    } 
    for (i = 0; i < size; i++) { 
        if (array[i] == sum - 2 * left_sum) { 
            return i; 
        } 
        left_sum += array[i]; 
    } 
    return -1; 
}

Let's walk through the logic

  1. The first loop calculates the total sum of the entire array and stores it in sum.
  2. The second loop iterates through each element, maintaining left_sum—the cumulative sum of elements to the left of the current index.
  3. The condition array[i] == sum - 2 * left_sum comes from rearranging the equilibrium check:
    • The sum of elements to the right of index i is sum - left_sum - array[i] (total sum minus left sum minus the current element).
    • We want left sum = right sum: left_sum = sum - left_sum - array[i]
    • Rearranging gives us the code's condition—this is a clever way to avoid recalculating the right sum every time.
  4. If an equilibrium index is found, the function returns it right away.

Why return -1?

Not every array has an equilibrium index! For example, take the array [1, 2, 3, 4]—no position exists where the left sum equals the right sum.

In cases like this, after checking every element and finding no match, the function returns -1 to signal that no equilibrium index exists in the input array. This is a standard convention in C for search-style functions: return -1 when the target isn't found (you'll see this pattern in standard library functions like strchr too).

So that -1 isn't a mistake—it's the proper way to handle the scenario where the array has no equilibrium point.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:57:00