c - 需要帮助理解此 C 代码(数组)

标签 c arrays

我需要帮助才能清楚地理解这段代码,请帮忙。我无法弄清楚该程序如何跟踪响应数组中给出的数字。 我不明白 for 循环发生了什么,特别是这一行++Frequency[responses[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;
    }

最佳答案

++Frequency[responses[answer]] 是一种密集的书写方式

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

需要注意的是,频率[r]仅评估一次。

因此,如果 answer 等于 0,则 responses[answer] 等于 1,因此我们添加 1频率[1]

编辑

下表显示了循环中频率发生的情况(旧值 => 新值):

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

等等

关于c - 需要帮助理解此 C 代码(数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39428649/

相关文章:

c - 如何释放另一个结构体内部的结构体

c - 选择小于架构大小的变量是一个有效的选择吗?

JavaScript 奇怪的对象

ios - 解码某些 Base64 字符串时出错,但不解码其他字符串

c# - 将字符串列表转换为字节数组

java - C#/Java如何存储二维数组,与C++有何不同?

C FILE* 读/写和可选创建

c - 如何使用 switch 条件来获取输入字符串的大写和小写

函数中无法识别字符数组

java - 如何将底层字节数组视为短裤数组?还是整数?还是多头?