2017-03-12 67 views
0

我試圖計算數組中特定行的平均值。 例如數組的格式如下:計算數組中特定行的平均值並存儲在另一個數組中

float Array[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,...20} 

我要計算的數組中的第5個數字的平均值,那麼接下來的5個數字的平均值等等......它們存儲到只有這些數字的平均值的另一個數組中。

這裏是我到目前爲止的代碼

float average_values[4]; 
for (int a = 0; a < 4; a++){ //20 elements in array divided by 5 = 4 
    float sum = 0; 
    for (int b = 0; b < (20/4); b++){ 
     sum = sum + scores[b]; 
    } 
    average_values[i] = sum/(20/4); 
} 

回答

1
#include <stdio.h> 
int main() 
{ 
     int scores[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20}; 
     float average_values[4]; 
     for (int a = 0; a < 4; a++) 
     { //20 elements in array divided by 5 = 4 
      float sum = 0; 
      for (int b = 0; b < (20/4); b++) 
       sum = sum + scores[b+a*5]; // THIS IS THE BIT YOU'D MISSED 
      average_values[a] = sum/(20/4); 
     } 
} 
0

保持拋開一切錯別字在你的職位

我假設你已經在填滿你的average_values陣列的麻煩。

所以假設scores陣列矩陣5列4行,

所以,你的內循環應該是這樣的:

for (int b = 0; b < 5; b++){ 
    sum = sum + scores[ a*5 + b]; 
         //~~~ Correct index for next sets 
} 
0

隨着range-v3,這將是:

auto means = Array 
      | ranges::view::chunk(5) 
      | ranges::view::transform([](auto&& r) { return ranges::accumulate(r, 0.f)/5; }); 

Demo

相關問題