Write a template function that returns the average of all the elements of an array.
The arguments to the function should be the array name and the size of the array
(type int). In main(), exercise the function with arrays of type int, long, double,
and char
#include <iostream>
using namespace std;
template <typename T>
double calculateAverage(T values[], int n){
double total = 0;
for (int i = 0; i < n; i++){
total += values[i];
}
return total/n;
}
int main(){
int size =5;
int intValues[] = {10, 10, 12, 445, 1};
double doubleValues[] = {1.5, 23.48, 41.89, 11.85,2.326};
long longValues[] = {13246, 222, 355, 7575,3333};
char charValues[] = {'l', 'u', 'q', 'z', 'p'};
cout << "Average of integers: " << calculateAverage<int>(intValues, size) << "\n";
cout << "Average of doubles: " << calculateAverage<double>(doubleValues, size) << "\n";
cout << "Average of long: " << calculateAverage<long>(longValues, size) << "\n";
cout << "Average of chars: " << calculateAverage<char>(charValues, size) << "\n";
system("pause");
}
Comments
Leave a comment