一段代码的后置条件

时间:2018-05-13 16:27:37

标签: java

Barron的APCS书中的一个问题要求考虑以下程序段:

// 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;

鉴于该段,我应该选择该段的最佳后置条件。给出的后置条件是:

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. 

D) a[0]...a[n-1] has been stripped of all nonnegative integers. 

C) a[0]...a[n-1] has been stripped of all occurrences of zero.

E) The updated value of n is less than or equal to the value of n before execution of the segment.

这本书说正确的答案是B.为什么?如果数组a仅包含负整数,则段末尾的n值为0,而[0] ... a [n-1]则为[0]。 ..A [-1]。

1 个答案:

答案 0 :(得分:3)

这本书的答案是错误的。

正确的答案是E。

假设n = 5,你有5个值a [i = 0,4] = {-1,-2,-3,4,5}

执行后a [i]的值为:{4,5,-3,4,5}

并且n = c = 2

函数读取:遍历列表,如果找到非负int(n> = 0),则用它的副本值更新数组的初学者。

因此c = non-negative int count

从这个观察中,你可以选择正确的答案。