我需要帮助才能清楚地理解这段代码,请帮忙。我无法弄清楚该程序如何跟踪响应数组中给出的数字。 我不明白 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/