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

APCS代码段后置条件疑问:为何正确答案为选项B?

Understanding the Postcondition of This APCS Code Snippet

Let’s start by restating the code and question clearly, then tackle your edge-case confusion head-on.

The Code Snippet

// Precondition: a[0]...a[n-1] is an initialized array of integers, and 0 < n <= a.length.
int c = 0;
for (int i = 0; i < n; i++) {
    if (a[i] >= 0) {
        a[c] = a[i];
        c++;
    }
}
n = c;

The Options

  • A) a[0]...a[n-1] has been stripped of all positive integers.
  • B) a[0]...a[n-1] has been stripped of all negative integers.
  • C) a[0]...a[n-1] has been stripped of all occurrences of zero.
  • D) a[0]...a[n-1] has been stripped of all nonnegative integers.
  • E) The updated value of n is less than or equal to the value of n before execution of the segment.

Your Question

The correct answer is listed as B, but you’re confused: if the array only contains negative integers, after execution n becomes 0, so a[0]...a[n-1] is a[0]...a[-1]—an empty range. Why does B still hold?


Breaking Down the Answer

Great question—this hinges on a key nuance in programming logic: how we interpret conditions for empty collections.

First, let’s parse what option B is actually claiming: the subarray defined by a[0] to a[n-1] contains no negative integers.

When n = 0, that subarray is empty (there are no elements between index 0 and -1). An empty collection automatically satisfies any "contains no X" condition because there are no elements to violate it. Think of it like saying "my backpack has no oranges"—that’s true even if my backpack is completely empty. There’s nothing to contradict the statement.

Let’s also reinforce why B is the best postcondition by ruling out the others:

  • A is wrong: the code keeps non-negative values (positives + zero), not removes them.
  • C is wrong: zero is explicitly kept (since the condition checks a[i] >= 0).
  • D is wrong: the code removes negatives, not non-negatives.
  • E is technically true, but it’s a vague side effect, not the core transformation the code performs. The question asks for the best postcondition, which should describe exactly what the code does to the array.

Even in the edge case where all elements are negative, B holds because the resulting empty subarray has no negative integers by default.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:25:48