Jump to content

Algorithms/Find average

From Wikibooks, open books for an open world

//This is a function to calculate the average of a set of numbers (such as test scores) in C++.

//If we have a set of N test scores x0, x1, x2, ..., xN-1, then the //average is (x0 + x1 + x2 + ... + xN-1) / N.

//Here, our set of test scores is represented as an array (x) //of N doubles. For more information on doubles, see "What are doubles?"

//"What are doubles?" //Doubles are floating-point numbers in the C++ //programming language. The important //thing to know about these is that their remainders do not truncate //in division. So if 3.0 is a floating-point number, then //3.0 / 2 = 1.5. In "integer division", the remainder would //have truncated and the answer would have been 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.

}