One way of getting average number for multiple numbers is to find the Cumulative Moving Average, or CMA:
Your code a + (b - a) / 2
can also be derived from this equation for n + 1 == 2
.
Translating above equation to code, you would get something similar to:
std::vector<int> vec{10, 5, 8, 3, 2, 8}; // average is 6
double average = 0.0;
for(auto n = 0; n < vec.size(); ++n)
{
average += (vec[n] - average) / (n + 1);
}
std::cout << average; // prints 6
Alternatively, you can also use the std::accumulate
:
std::cout << std::accumulate(vec.begin(), vec.end(), 0.0,
[n = 0](auto cma, auto i) mutable {
return cma + (i - cma) / ++n;
});
Do note any time you are using floating division can result into imprecise result, especially when you attempt to do that for numerous times. For more regarding impreciseness, you can look at: Is floating point math broken?