当前位置:网站首页>Several methods of calculating the average value of two numbers

Several methods of calculating the average value of two numbers

2022-07-07 08:52:00 Please Sit Down

Method 1 : Directly find the average ( Add two numbers and divide by two )

int average(int x,int y){
    return (x + y) / 2;
}

This algorithm has some defects , When x and y When large enough x and y And there will be data overflow , So we can't get the result we want .( It is not recommended to use )

Method 2 :x + y And x Divide by 2 And , Data overflow can be avoided

int average(int x,int y){
    return x + (y - x) / 2;
}

  Method 3 : Improvement method version II ( Displacement )

int average(int x,int y){
    return x + ((y - x) >> 1);
}

  Method four : Using bit operations - Intersection plus half of difference ( Rounding down )

int average(int x,int y){
    return (x & y) + ((x ^ y) >> 1);
}

  Method five : Using bit operations -  Intersection plus half of difference ( Rounding up )

int average(int x,int y){
    return (x | y) - ((x ^ y) >> 1);
}

Method four 、 V see link : The magic of bit operation - Find the average of two integers - You know  

原网站

版权声明
本文为[Please Sit Down]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130629582239.html