使用数组汇总调查结果

时间:2016-12-12 17:12:29

标签: c arrays

此示例来自如何编程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;
}

2 个答案:

答案 0 :(得分:2)

这很简单。

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;
} 

(这称为&#34;提取局部变量&#34;重构)。

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

然后用事实填充frequency

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

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

答案 1 :(得分:0)

只是为了理解代码重写这个循环

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

以下方式:)

for ( answer = 0; answer < RESPONSES_SIZE; ++answer )
{
    rating = responses[ answer ];

    switch ( rating )
    {
    case 1:
        frequency[1] = frequency[1] + 1;
        break;
    case 2:
        frequency[2] = frequency[2] + 1;
        break;
    case 3:
        frequency[3] = frequency[3] + 1;
        break;
    case 4:
        frequency[4] = frequency[4] + 1;
        break;
    case 5:
        frequency[5] = frequency[5] + 1;
        break;
    case 6:
        frequency[6] = frequency[6] + 1;
        break;
    case 7:
        frequency[7] = frequency[7] + 1;
        break;
    case 8:
        frequency[8] = frequency[8] + 1;
        break;
    case 9:
        frequency[9] = frequency[9] + 1;
        break;
    case 10:
        frequency[10] = frequency[10] + 1;
        break;
    }
}