使用位操作符计算两个整数的平均数,不会发生溢出
average.cpp内容如下:
#include <iostream>
using namespace std;
int average(int a, int b)
{
return (a & b) + ((a ^ b) >> 1);
}
int main(int argc, char** argv)
{
int a = 123456789;
int b = 23456789;
cout << "average of " << a << " and " << b << " is: " << average(a, b) << endl;
return 0;
}
运行结果如下: