我需要帮助以清楚地了解此代码,请提供帮助。我无法弄清楚这个程序如何跟踪响应数组中给出了多少个数字。
我不明白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;
请注意,
frequency[r]
仅计算一次。因此,如果
answer
等于0
,则responses[answer]
等于1
,因此我们将1
添加到frequency[1]
。编辑
下表显示了
frequency
在循环中发生的情况(旧值=>新值):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/