How to get an average in C++?

If you have the values in a vector or an array, just use std::accumulate from <numeric>:

std::vector<double> vec;
// ... fill vec with values (do not use 0; use 0.0)
double average = std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size();

Leave a Comment