需要帮助理解这个C代码(数组)

时间:2016-09-10 17:19:58

标签: c arrays

我需要帮助才能清楚地理解此代码,请帮忙。我无法弄清楚这个程序如何跟踪响应数组中给出的数量。 我不明白for循环中的内容,特别是这行++频率[回复[answer]];

    #include<stdio.h>
    #define RESPONSE_SIZE 40
    #define FREQUENCY_SIZE 11

    int main(void)
    {
        int answer; /* counter to loop through 40 responses */
        int rating; /* counter to loop through frequencies 1-10 */

        /* initialize frequency counters to 0 */

        int frequency[FREQUENCY_SIZE] = {0};

        /* place the survey responses in the responses array */

        int responses[RESPONSE_SIZE] = {1,2,6,4,8,5,9,7,8,10,1,6,3,8,6,10,3,8,2,7,6,5,7,6,8,6,7,5,6,6,5,6,7,5,6,4,8,6,8,10};

        /* for each answer, select value of an element of array responses
        and use that value as subscript in array frequency to determine element to increment */

        for(answer = 0 ; answer < RESPONSE_SIZE; answer++){
            ++frequency[responses[answer]];
        }

        printf("%s%17s\n", "Rating", "Frequency");

        /* output the frequencies in a tabular format */
        for(rating = 1; rating < FREQUENCY_SIZE; rating++){
            printf("%6d%17d\n", rating, frequency[rating]);
        }

        return 0;
    }

2 个答案:

答案 0 :(得分:0)

for(answer = 0 ; answer < RESPONSE_SIZE; answer++){
    ++frequency[responses[answer]];     //  <---
}

上面的循环只计算一个数字出现在数组responses中的次数,并存储在数组frequency中该数字的索引处。这一行在第一个循环中执行 -

 ++frequency[responses[answer]];

因此,它会增加数组responses[answer]的索引frequency的值。

假设responses[answer]的值为1,则数组1的索引frequency的值会递增。

第二个for循环仅用于输出,如上所述。

答案 1 :(得分:0)

++frequency[responses[answer]]是一种密集的写作方式

int r = response[answer];
frequency[r] = frequency[r] + 1;

警告frequency[r]仅评估一次。

因此,如果answer等于0,则responses[answer]等于1,因此我们将1添加到frequency[1]

修改

下表显示了frequency通过循环发生的情况(旧值=&gt;新值):

answer    response[answer]    frequency[response[answer]]
------    ----------------    ---------------------------
     0                   1           frequency[1]: 0 => 1
     1                   2           frequency[2]: 0 => 1
     2                   6           frequency[6]: 0 => 1
     3                   4           frequency[4]: 0 => 1
   ...                 ...           ...
    10                   1           frequency[1]: 1 => 2