C语言equilibrium函数返回-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
- The first loop calculates the total sum of the entire array and stores it in
sum. - The second loop iterates through each element, maintaining
left_sum—the cumulative sum of elements to the left of the current index. - The condition
array[i] == sum - 2 * left_sumcomes from rearranging the equilibrium check:- The sum of elements to the right of index
iissum - 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.
- The sum of elements to the right of index
- 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

