Java 程式用於計算 Java 中數字的平均值


一堆數字的平均值是它們的和除以它們的數量。它可以定義為 −

average = sum of all values / number of values

在這裡,我們將學習如何以程式設計方式計算平均值。

演算法

1. Collect integer values in an array A of size N.
2. Add all values of A.
3. Divide the output of Step 2 with N.
4. Display the output of Step 3 as average.

示例

線上演示

public class AverageOfNNumbers {
   public static void main(String args[]){
      int i,total;
      int a[] = {0,6,9,2,7};
      int n = 5;
      total = 0;

      for(i=0; i<n; i++) {
         total += a[i];
      }
      System.out.println("Average ::"+ total/(float)n);
   }
}

輸出

Average ::4.8

更新於: 13-Mar-2020

14K+ 瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.