跳轉至內容

Algorithms/查詢平均值

來自華夏公益教科書,面向開放世界的開放書籍

//這是一個用 C++ 計算一組數字(例如考試成績)平均值的函式。

//如果我們有一組 N 個考試成績 x0、x1、x2,...,xN-1,則//平均值為 (x0 + x1 + x2 + ... + xN-1) / N。

//在此,我們的一組考試成績表示為一個數組(x)//代表 N 個雙精度數。有關雙精度數的更多資訊,請參見“什麼是雙精度數?”

//"什麼是雙精度數?"//雙精度數是 C++//程式語言中的浮點數。//要知道的重要一點是,這些數在除法中不會截斷餘數。//因此,如果 3.0 是一個浮點數,則//3.0 / 2 = 1.5。在“整數除法”中,餘數//已經截斷,答案將為 1)。

double average(double x[], int N) {

   double sum = 0; //This will represent the sum of our test scores.
   //Get the sum of all our testScores, from x0 to xN-1, inclusive.
   for (int i = 0; i < N; i++) {
       sum = sum + x[i]; //Adds the xi, where 0 <= i <= N - 1, to our sum so far.
   }
   return sum / N; //Now divide. Sum is a double. Therefore, its remainder
   //will not truncate. So if N = 11 and sum == 122, then the average
   //will be (approximately) 11.090909 instead of 11.

}

華夏公益教科書