两个变量a,b,不用判断语句,找出两个中比较大的那个变量

法一:位运算ios

          

[cpp] view plaincopyprint?数组

  1. #include <iostream>  spa

  2.   

  3. using namespace std;  .net

  4.   

  5. int my_max(int x,int y)  code

  6. {  blog

  7.     int test[2]={x,y};  get

  8.     unsigned int c;  io

  9.   

  10.         c=x-y;  class

  11.           

  12.         c>>=31;  test

  13.         return test[c];  

  14. }  

  15. int main()  

  16. {  

  17.     int a=7,b=11;  

  18.    // cout<<my_max(a,b)<<endl;  

  19.     // int c=a-b;  

  20.     cout<<my_max(a,b)<<endl;  

  21.     system("pause");  

  22.     return 0;  

  23. }  

#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?

  1. int max=((a+b)+abs(a-b))/2;  

  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;

         这种方法是算出来的,并不是像上面那样找出来的,但在别的时候也许会用到,所以也许留意一下

相关文章
相关标签/搜索