Back to General discussions forum
Hi, i have some a problem with the task # 16 (Average of an Array). My function that calculates avg:
int avg(std::vector<int>& v){
v.pop_back(); // Removes 0
return std::accumulate(v.begin(),v.end(),0) / v.size();
}
Input data:
11
312 142 146 117 192 292 55 329 0
483 5119 5623 3236 73 15013 11739 14547 11459 6360 15967 14875 0
387 240 392 222 474 48 347 274 0
12482 12168 8647 14215 6286 3313 13675 6768 8431 0
2126 386 1340 1667 3251 2930 0
172 2634 1867 2091 1670 3639 1787 2049 2311 0
8575 12004 10025 837 9834 16311 4149 7125 6695 12580 10039 315 4699 11581 5673 0
126 154 414 212 1471 1347 1257 258 1118 102 1282 225 0
1297 1543 220 1402 724 0
12912 8375 11553 6566 8689 16252 0
11233 9959 15367 12464 13263 673 0
My answer:
198 8707 298 9553 1950 2024 8029 663 1037 10724 10493
Expected answer:
198 8708 298 9554 1950 2024 8029 664 1037 10725 10493
As you can see, some values has a different of 1 unit, i don't know why.. Maybe some conversion due to the division by the array size?
Hi, it looks like your code is rounding down, but it should be rounding to the nearest integer
Thanks, now it works:
int avg(std::vector<int>& v){
v.pop_back(); // Removes 0
return std::round(std::accumulate(v.begin(),v.end(),0.0f) / v.size());
}