gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:08:23 25 4
gpt4 key购买 nike

这个例子来自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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com