# Calculating average/mean of different type arrays with one function?

I have a few arrays, some of them are float some of them az int (uint16_t, analog readings). I would like to write a method that can calsulate the mean value of all of them. Here is what I got right know. The problem is that the function can’t receive arrays with non floats.

``````#define NUM_OF_READINGS 5
uint16_t avg1;
float avg2;

void setup() {
Serial.begin(9600);
avg1 = average(array1);
avg2 = average(array2);
Serial.println(avg1);
Serial.println(avg2);
}

void loop() {

}

float average (float *array) {
float sum = 0L ;
for (int i = 0 ; i < NUM_OF_READINGS ; i++){
sum += array [i] ;
}
return  ((float) sum) / NUM_OF_READINGS ;
}
``````

Can I modify somehow the function, or do I need 2 functions for each types?

you could use a template

I aproached it a little bit different. Every arrays are float, but where it is needed, the average variable is integer, and I use tha “+0.5” trick to round the float from the function to int.

``````#define NUM_OF_READINGS 5
uint16_t avg1;
float avg2;

void setup() {
Serial.begin(9600);
avg1 = average(array1) + 0.5;
avg2 = average(array2);
Serial.println(avg1);
Serial.println(avg2);

}

void loop() {

}

float average (float *array) {
float sum = 0L ;
for (int i = 0 ; i < NUM_OF_READINGS ; i++){
sum += array [i] ;
}
return  ((float) sum) / NUM_OF_READINGS ;  // average will be fractional, so float may be appropriate.
}
``````