不使用if、?:、switch及其他判断语句如何找出两个int型变量中的最大值和最小值
方法一:利用绝对值的方法
int max = ((a+b)+abs(a-b))/2
int min = ((a+b)-abs(a-b))/2
如果a>b,则max = a;如果a<b,则max= b.
方法二:对变量的差值进行位移操作,通过其是否为非0值确定两个变量的大小
int a = 3;
int b = 4;
int c = a - b;
int max = (unsigned)c >> (sizeof(int) * 8 - 1);
if (!max)
cout << a << endl;
else
cout << b << endl;
输出结果为:4
方法三:通过加减运算与位移运算结合的方式实现
int a = 3;
int b = 4;
int min = a + (((b - a) >> 31) & (b - a));
int max = a - (((a - b) >> 31)&(a - b));
cout << min << " " << max << endl;
输出结果为:3 4