2012-09-16 88 views
-1

如何計算數組的平均值,然後將其插入另一個數組並將其輸出到控制檯中。 例如,我有尺寸100的陣列,並且我想計算數的平均值在陣列中,然後在尺寸的陣列插入5.計算數組的平均值並插入另一個陣列

+1

如果你正在計算一個平均值爲什麼第二個大小爲5的數組?這個作業也是? – Borgleader

+0

我不想計算一個平均值,我需要計算大小爲100的數組中的5個平均值,並且不是它不是功課。只是我似乎無法完成我的程序。 – user1675031

+1

那麼你會計算前20個元素的平均值,然後是下20個元素等等? – Borgleader

回答

0

這裏是做的一種方法:

public class Main 
{ 
    public static void main(String[] args) 
    { 
     float averages[] = new float[5]; 
     int aLotOfNumbers[] = new int[100]; 

     // Initialize the numbers to 0, 1, 2, 3, 4, ..., 99 
     for(int i=0; i<100; i++) 
     { 
      aLotOfNumbers[i] = i; 
     } 

     // Compute the averages by summing groups of 20 numbers and dividing the sum by 20 
     for(int i=0; i<5; i++) 
     { 
      float runningSum = 0.0f; 
      for(int j=0; j<20; j++) 
      { 
       runningSum += aLotOfNumbers[i*20 + j];    
      } 
      averages[i] = runningSum/20.0f; 
     } 

     // Print the 5 average values 
     for(int i=0; i<5; i++) 
     { 
      System.out.println("Average[" + i + "] = " + averages[i]); 
     } 
    } 
} 
+0

謝謝你,將與此合作。 – user1675031