法一:位运算ios
[cpp] view plaincopyprint?数组
#include <iostream> spa
using namespace std; .net
int my_max(int x,int y) code
{ blog
int test[2]={x,y}; get
unsigned int c; io
c=x-y; class
c>>=31; test
return test[c];
}
int main()
{
int a=7,b=11;
// cout<<my_max(a,b)<<endl;
// int c=a-b;
cout<<my_max(a,b)<<endl;
system("pause");
return 0;
}
#include <iostream> using namespace std; int my_max(int x,int y) { int test[2]={x,y}; unsigned int c; c=x-y; c>>=31; return test[c]; } int main() { int a=7,b=11; // cout<<my_max(a,b)<<endl; // int c=a-b; cout<<my_max(a,b)<<endl; system("pause"); return 0; }
在my_max()中,经过对无符号数c右移31位,可得(a-b)的符号位,可知其为正仍是为负,这样返回数组中相应的变量便可。
注意:对于有符号位数的位移,当右移时:1 .最高位是1,即负数,那么右移时不断补1;
2. 最高位是0,即正数,那么右移时不断补0;
对于无符号数的位移,当右移时:只补0;
所以,题中的无符号整形数c右移便可获得其符号位。
法二:
[cpp] view plaincopyprint?
int max=((a+b)+abs(a-b))/2;
int min=((a+b)-abs(a-b))/2;
int max=((a+b)+abs(a-b))/2; int min=((a+b)-abs(a-b))/2;
这种方法是算出来的,并不是像上面那样找出来的,但在别的时候也许会用到,所以也许留意一下