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

标签 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 ] ]; 这是如何工作的,我无法理解它的逻辑。它会增加其中的每个值还是什么?

最佳答案

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

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

你应该知道 ++frequency[index]

是一样的
frequency[index] = frequency[index]+1

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

关于你能解释一下这个例子中的频率数组逻辑吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41057335/

相关文章:

c - 是否可以手动检查 c 中的内存对齐?

c - GtkScrolledWindow + WebkitWebView 滚动

c - 在处理 .wav 文件时我应该使用哪种 fopen() 模式?

c - 是否可以通过 mmap 匿名内存访问 "punch holes"?

c - sublime text 2错误5访问被拒绝

c - 避免过度转换

c - 将 uint8_t 中的位地址作为结构体的成员

C 链接术语差异

c - pthread中PTHREAD_CREATE_JOINABLE的用法是什么?

c - 我可以改变指针的功能吗?