So, while solving a leetcode problem : Median of Two Sorted Arrays, I came across a problem with general vector elements addition and storing the result into a double.
Here is what did not work :
return median = (result[r/2-1] + result[r/2]) / 2;
Output : It wouldn’t return correct values. Say the
3 in an array
[1,2,3,4]. The output should be
2.5 which is the median. But instead of this it always return
2 as the median.
What worked :
n = result[r/2-1]; median = (n + result[r/2]) / 2; return median;
Its the same exact formula with substitutions. Can anyone explain me why does this happen?
Here’s the link to entire code : https://leetcode.com/submissions/detail/511995065/
Source: Windows Questions C++