What is the right way to find the average of two values?

后端 未结 8 1141
北荒
北荒 2021-02-19 00:58

I recently learned that integer overflow is an undefined behavior in C (side question - is it also UB in C++?)

Often in C programming you need to find the average of two

8条回答
  •  灰色年华
    2021-02-19 01:22

    (a >> 1) + (b >> 1) + (((a & 1) + (b & 1)) >> 1)
    

    The shift statement (x >> i) in c int mathematics is equivalent to a division by 2 to the power of i. So the statement (a >> 1) + (b >> 1) is the same as a/2 + b/2. However the mean of the truncated parts of the number need to be added as well. This value can be obtained by masking (a & 1), adding ((a & 1) + (b & 1)) and dividing (((a & 1) + (b & 1)) >> 1). The mean becomes (a >> 1) + (b >> 1) + (((a & 1) + (b & 1)) >> 1)

    Note: the reason to use >> and & rather than / and % as the division and remainder operators is one of efficiency.

提交回复
热议问题