2016-12-09 71 views
0

它是一個簡單的,但有一個與嵌套數組你能解釋一下這個例子中的頻率數組邏輯嗎?

/*2 Student poll program */ 
#include <stdio.h> 
#include<stdlib.h> 
#include<time.h> 
#include<math.h> 

#define RESPONSE_SIZE 40 
#define FREQUENCY_SIZE 11 

int main() 
{ 
    int answer; 
    int rating; 

    /* place survey responses in array responses */ 
    int frequency[ FREQUENCY_SIZE ] = { 0 }; 

    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 ] ]; // this part is complex for me, can you please explain it further? 
     } 
     printf("%s%17s\n", "Rating", "Frequency"); 

    /* output frequencies in tabular format */ 
     for (rating = 1; rating < FREQUENCY_SIZE; rating++) { 
      printf("%6d%17d\n", rating, frequency[ rating ]); 
     } 
     _sleep(1000*100); 

     return 0; 
} 

++frequency[ responses [ answer ] ];是如何工作的問題,我無法抓住它的邏輯。它增加了它的每個值或什麼?

回答

2
++frequency[ responses [ answer ] ]; 

是簡寫

frequency[ responses [ answer ] ] = frequency[ responses [ answer ] ] + 1; 

你可以找到關於增加經營here更多細節。

2

這是寫這個相同代碼的方式有些含糊:

int index = responses[answer]; 
++frequency[index]; 

,你應該知道,++frequency[index]相同

frequency[index] = frequency[index]+1 

的代碼只增加一個數值加1前綴或後綴++在這裏並不重要。

1

++frequency[ responses [ answer ] ];這實際上增加了它。這裏的索引是的responses數組,並且增加到frequency。因此,它可以代替使用++a,您可以使用:

a = a+1; 
相關問題