Plan for Mean
The mean of a list of values is the sum of those values divided by the number of values. In the case of the statistics calculator, we already have a sum
function, so the mean
function can just call sum
and use the result returned.
To get the number of elements in the array we needed to keep track of this ourselves as C does not retain any details about the length of the arrays you declare. This is why we have the size
field in our number_data
struct, so we will have the number of elements when we are asked to calculate the mean.
Have a go at coding this yourself.
- /* stats-calc.cpp - from the field guide. written by ... */#include <cstdio>#include "utilities.h"// The maximum number of values we can storeconst int MAX_NUMBERS = 20;/*** The data structure to store the numbers** @field values the array of values* @field size the number of values in the array - up to MAX_NUMBERS*/struct number_data{double values[MAX_NUMBERS];int size;};/*** Populate the array with values entered by the user** @param data the array of values (passed by reference)*/void populate_array(number_data &data){int size = read_integer("How many values do you want to enter? ");if (size > MAX_NUMBERS){printf("Sorry, you can only enter %d values.\n", MAX_NUMBERS);size = MAX_NUMBERS;}else if (size < 0){size = 0;}data.size = size;// Populate each element - up to data.sizefor (int i = 0; i < data.size; i++){data.values[i] = read_double("Enter value: ");}}/*** Output the values in the array** @param data the array of values*/void print(const number_data &data){for (int i = 0; i < data.size; i++){printf("%d: %lf\n", i, data.values[i]);}}/*** Calculate the sum of the values in the array** @param data the array of values* @return the sum of the values*/double sum(const number_data &data){int i;double result = 0;for (i = 0; i < data.size; i++){result += data.values[i];}return result;}/*** Calculate the mean of the values in the array** @param data the array of values* @returns the mean of the values*/double mean(const number_data &data){if (data.size > 0)return sum(data) / data.size;elsereturn 0;}//todo: add max hereint main(){number_data data = {{},0};populate_array(data);printf("\nYou entered...\n\n");print(data);printf("\nCalculating statistics...\n\n");printf("Sum: %4.2lf\n", sum(data));printf("Mean: %4.2lf\n", mean(data));return 0;}
Once you are finished, make sure you check that this works before moving on.