Vector elements addition and storing it into a double [closed]

  c++

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 result[r/2-1] and result[r/2] are 2, 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 result[r/2-1], i.e 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++

LEAVE A COMMENT