c - 使用数组汇总调查结果

标签 c arrays

这个例子来自How to program c book

40 名学生被要求对餐厅的食物质量进行评分 学生食堂的评分为 1 到 10(1 表示糟糕,10 表示 出色的)。将 40 个响应放在一个整数数组中并进行汇总 投票结果。


我一直在理解这个例子中使用的算法,无法理解它,如果你能简化它,请提前感谢

// Analyzing a student poll.
#include <stdio.h>
#define RESPONSES_SIZE 40 // define array sizes
#define FREQUENCY_SIZE 11
int main( void ) {
size_t answer; // counter to loop through 40 responses
size_t 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[ RESPONSES_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 < RESPONSES_SIZE; ++answer )
{
    frequency[ responses [ answer ] ]=frequency[ responses [ answer ] ]+1;
} // end for
// display results
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 ] );
} // end for
// end main
return 0;
}

最佳答案

这很简单。

for ( answer = 0; answer < RESPONSES_SIZE; ++answer )
{
    frequency[ responses [ answer ] ]=frequency[ responses [ answer ] ]+1;
} 

... 遍历 answer 数组,并针对其中的每个值更新该值的 frequency 元素。可以通过以下方式使其更清楚:

for ( answer = 0; answer < RESPONSES_SIZE; ++answer )
{
    int response = responses[answer];
    frequency[response]=frequency[response]+1;
} 

(这称为“提取局部变量”重构)。

因此,如果 responses 中的第一个值为 5,那么它要做的第一件事就是将 frequency[5] 中的 0 替换为 0 + 1 == 1

然后用事实填充频率:

for ( rating = 1; rating < FREQUENCY_SIZE; ++rating )
{
    printf( "%6d%17d\n", rating, frequency[ rating ] );
}

...循环遍历 frequency 打印每个元素的索引和内容。

关于c - 使用数组汇总调查结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41106021/

相关文章:

c - 在 Linux 中使用 SMTP 通过 C 发送电子邮件

python - Cython:如何将 C 函数分配给 Python/Cython 变量?

c - C 中的数组赋值使用指针运算

更改函数内的矩阵并在 main 中使用它

c - 如何将 "\r"打印到文件

c - 我们如何确定这段代码中开头的 'b' 的值是 0

c - 动态数组添加元素后打印乱码

PHP:有没有一种简单的方法可以将数字列表(作为字符串,如 "1-3,5,7-9")解析为数组?

c# - 需要使用返回类型字符串数组方法

python - 在 numpy 数组中查找连续重复的 nan