2016-09-10 8 views
-3

私はこのコードをはっきりと理解する助けが必要です。私はこのプログラムがどのくらい多くの数が応答配列で与えられたかを把握している方法を理解できません。 私はforループと特にこの行に何が起こっているのか分かりません++ frequency [responses [answer]];このCコード(アレイ)を理解する助けが必要です

#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; 
    } 
+0

任意のCチュートリアルは、アレイへのアクセスを説明しなければなりません。このコードは、一方の配列の値を他方のインデックスのインデックスとして使用します。コメントでもそう言われています。 5月かそれとも意味がないかもしれません。 – Robert

答えて

0

++frequency[responses[answer]]frequency[r]は一度だけ評価されていることを警告して

int r = response[answer]; 
frequency[r] = frequency[r] + 1; 

を書くの密な方法です。

answer0に等しいのであれば、その後、responses[answer]1に等しいので、私たちはfrequency[1]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 

+0

intresponse [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}; 答えが0の場合、応答[回答]は1に等しいので、頻度[1]に1を加算します。その後、私たちは再び10番目のレスポンスで1番に遭遇します。 答えが10の場合、応答[回答]は1に等しいので、再び周波数[1]に1を加算します。したがって、インデックス頻度[1]の値は2?右 ? – Shateel

+0

@Shateel:私の編集を参照してください。 –

+0

明らかに理解されています!ありがとう、あなたは素晴らしいです! – Shateel

0
for(answer = 0 ; answer < RESPONSE_SIZE; answer++){ 
    ++frequency[responses[answer]];  // <--- 
} 

これ以上のループは、単に数が配列responsesに表示された回数をカウントし、その配列frequencyにその番号のインデックスに格納されています。

++frequency[responses[answer]]; 

だから、それはアレイfrequencyの指標responses[answer]に値をインクリメントする - この行は、最初のループではないこと。

responses[answer]の値が1であるとすると、配列frequencyのインデックス1の値がインクリメントされます。

第2のforループは前述のように出力されます。

関連する問題