Why prefer start + (end - start) / 2 over (start + end) / 2 when calculating the middle of an array?

后端 未结 4 1587
时光说笑
时光说笑 2020-11-29 17:02

I\'ve seen programmers use the formula

mid = start + (end - start) / 2

instead of using the simpler formula

mid = (start +          


        
4条回答
  •  被撕碎了的回忆
    2020-11-29 17:46

    To add to what others have already said, the first one explains its meaning clearer to those less mathematically minded:

    mid = start + (end - start) / 2
    

    reads as:

    mid equals start plus half of the length.

    whereas:

    mid = (start + end) / 2
    

    reads as:

    mid equals half of start plus end

    Which does not seem as clear as the first, at least when expressed like that.

    as Kos pointed out it can also read:

    mid equals the average of start and end

    Which is clearer but still not, at least in my opinion, as clear as the first.

提交回复
热议问题