Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::accumulate is rounding to an integer [duplicate]

Tags:

c++

I have the following code which returns me the sum of the last count elements in a vector of doubles foo:

return std::accumulate(foo.rbegin().base() - std::min(count, foo.size()), foo.rbegin().base(), 0);

But it is ignoring any decimal part. Why?

like image 865
P45 Imminent Avatar asked Feb 11 '26 03:02

P45 Imminent


1 Answers

It's surprisingly simple.

The type of the final parameter sets the type of the return of std::accumulate.

The simplest thing to do is use 0.0 in place of your final 0:

return std::accumulate(foo.rbegin().base() - std::min(count, foo.size()), foo.rbegin().base(), 0.0);

like image 185
Bathsheba Avatar answered Feb 18 '26 14:02

Bathsheba