Overflow When Calculating Average?

  c++, math, overflow

Given 2 integer numbers we can calculate their average like this:

return (a+b)/2;

which isn’t safe since (a+b) can cause overflow (Side Note: can someone tell me the correct term for this case maybe memory overflow?)

So we write:

return a+(b-a)/2;

can the same trick be implemented over n numbers and how?

Source: Windows Questions C++

LEAVE A COMMENT