你能解释一下这个例子中的频率数组逻辑吗?

时间:2016-12-09 09:41:53

标签: c

它很简单,但嵌套数组存在问题

/*2 Student poll program */
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>

#define RESPONSE_SIZE 40
#define FREQUENCY_SIZE 11

int main()
{
    int answer;
    int rating;

    /* place survey responses in array responses */
    int frequency[ FREQUENCY_SIZE ] = { 0 };

    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 ] ]; // this part is complex for me, can you please explain it further?
        }
        printf( "%s%17s\n", "Rating", "Frequency" );

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

        return 0;
}  

++frequency[ responses [ answer ] ];这是如何工作的,我无法理解它的逻辑。它会增加它中的每个值还是什么?

3 个答案:

答案 0 :(得分:2)

++frequency[ responses [ answer ] ];

的简写
frequency[ responses [ answer ] ] = frequency[ responses [ answer ] ]  +  1;

您可以找到有关增量运算符here的更多详细信息。

答案 1 :(得分:2)

编写这段相同的代码有点不太清楚:

int index = responses[answer];
++frequency[index];

您应该知道++frequency[index]

相同
frequency[index] = frequency[index]+1

代码只增加一个值1.前缀或后缀++在这里无关紧要。

答案 2 :(得分:1)

++frequency[ responses [ answer ] ];这实际上增加了它。此处索引为answer数组的responses,并添加到frequency。因此,它可以使用:

,而不是使用++a
a = a+1;