两个变量a,b,不用“if”,“? :”,switch或者其它判断语句,找出两个数中间比较大的

来源:互联网 发布:java mail ssl 发送 编辑:程序博客网 时间:2024/04/25 16:08

问题

有两个变量a,b,不用“if”,“? :”,switch或者其它判断语句,找出两个数中间比较大的。

解决方案

//--------------------------------------------------- 
// 环境:VS2005 
// 用途:比较两个数大小测试 
// 时间:2010.9.25 
// 作者:http://pppboy.blog.163.com
//--------------------------------------------------- 
#include "stdafx.h" 
#include <iostream> 
using namespace std; 
/* 
方法1:取平均值法 
大的为 ((a+b)+abs(a-b)) / 2 
小的为 (a+b - abs(a-b)) / 2 
*/ 
int fMax1(int a, int b) 
{     
    return  ((a+b)+abs(a-b)) / 2;  
} 
/* 
方法2:不使用abs() 
a<b时,a/b=0,所以前面为b*(b/a),后面为b/a,那么结果就是b 
a=b时,a/b=1,所以前面为a+b=2a,后面为2,那么结果就是a 
a>b时,b/a=0,所以前面为a*(a/b),后面为a/b,那么结果就是a 
*/ 
int fMax2(int a, int b) 
{ 
    int larger = (a*(a/b) + b*(b/a))/(a/b + b/a); 
    //long smaller = (b*(a/b) + a*(b/a))/(a/b + b/a); 
    return larger; 
} 
/* 
方法3:如果取 a/b 余数不为0,则说明a>b 
这是个好方法,不过题目说了,不能用“? :” 
*/ 
int fMax3(int a, int b) 
{ 
    return  (a / b) ? a : b; 
} 
/* 
方法4:移位法 
当b<0的时候以补码存,故最高位是1 
所以右移31位b>>31其实就是最高位的值 
b>=0时候最高位为0 
所以b跟1与时候为b,a=a-(a-b)=b 
b跟1作与运算时候为0,相当于a=a-0=a  
*/ 
int fMax4(int a, int b) 
{ 
    b = a - b; 
    a -= b & (b>>31);                    
    return a; 
} 
//移位法 
int fMax5(int a,int b) 
{ 
    int  c[2] = {a, b}; 
    int z = a - b; 
    z = (z>>31)&1; 
    return c[z]; 
} 
//移位法 
int  fMax6(int a, int b) 
{ 
    int flag = ((a - b) >> 31)&1; 
    return a - (a - b) * flag; 
} 
//我想这个应该是最牛B的一个 
int fMax7(int a, int b) 
{ 
    int pair[2] = {a, b};  
    return pair[a < b]; 
} 
int main(int argc, char* argv[]) 
{ 
    int a, b; 
    cout << "-------------------------------------------------" << endl; 
    cout << "input a :" << endl; 
    cin >> a; 
    cout << "input b :" << endl; 
    cin >> b; 
    cout << "-------------------------------------------------" << endl; 
    cout << "a = " << a << endl; 
    cout << "b = " << b << endl; 
    cout << "-------------------------------------------------" << endl; 
    cout << "(fMax1)the max number is : " << fMax1(a, b) << endl; 
    cout << "(fMax2)the max number is : " << fMax2(a, b) << endl; 
    cout << "(fMax3)the max number is : " << fMax3(a, b) << endl; 
    cout << "(fMax4)the max number is : " << fMax4(a, b) << endl; 
    cout << "(fMax5)the max number is : " << fMax5(a, b) << endl; 
    cout << "(fMax6)the max number is : " << fMax6(a, b) << endl; 
    cout << "-------------------------------------------------" << endl; 
    system("pause"); 
    return 0; 
} 

结果为:

------------------------------------------------- 
input a : 
54 
input b : 
78 
------------------------------------------------- 
a = 54 
b = 78 
------------------------------------------------- 
(fMax1)the max number is : 78 
(fMax2)the max number is : 78 
(fMax3)the max number is : 78 
(fMax4)the max number is : 78 
(fMax5)the max number is : 78 
(fMax6)the max number is : 78 
------------------------------------------------- 
请按任意键继续. . .