- 论坛徽章:
- 0
|
不用判断语句,求两个数的最大值
只用逻辑运算完成!
_isA递归函数用到了判断,但在使用中可以循环展开以不用判断语句。
注:以下用到了乘法,但是都是用0或1去乘一个数,这很容易用逻辑运算实现。其实,用逻辑运算可实现c程序用到的一切,处理器芯片内部都是用的逻辑门啊。
#include <stdio.h>;
#include <signal.h>;
#define UNSIGNED_INT 0
#if UNSIGNED_INT
unsigned int _A = 0xfffffff1;
unsigned int _B = 0xfff1ffff;
#else
int _A = 0x0f8ffff1;
int _B = 0xff2ffff3;
#endif
/* return bit i of variable A
*/
int A( int i )
{
return ((unsigned int)_A & (1 << i)) >;>; i;
}
/* return bit i of variable B
*/
int B( int i )
{
return ((unsigned int)_B & (1 << i)) >;>; i;
}
/* if A(i) >;= B(i), then return 1; else return 0;
*/
int bigger_eq( int i )
{
return A(i) | !B(i);
}
/* if A(i) >; B(i), then return 1; else return 0;
*/
int bigger( int i )
{
return A(i) & !B(i) ;
}
/* compare first (i+1) bits of A and B
if A >;= B; then return 1; else return 0;
*/
int _isA( i )
{
if( i <= 0 )
return bigger(i) | bigger_eq(i);
return bigger(i) | ( bigger_eq(i) & _isA(i-1) );
}
#if UNSIGNED_INT
unsigned int uis()
{
int s;
s = _isA(31);
return s*_A + (!s)*_B;
}
#else
int is()
{
int sA,sB;
int s;
sA = A(31);
sB = B(31);
s = _isA(30);
/*
sA sB s isA
0 0 * s
1 0 * 0
0 1 * 1
1 1 * s
*/
#define isA \
( \
((sA^sB) & sB) \
| \
( \
(!(sA^sB)) & s \
) \
)
printf( "s=%d,sA=%d,sB=%d\n", s, sA, sB );
return isA*_A + (!isA)*_B;
}
#endif
int main()
{
int i=0;
printf( "A=" );
for( i=31; i>;=0; i-- )
printf( "%d", A(i) );
printf( "\nB=" );
for( i=31; i>;=0; i-- )
printf( "%d", B(i) );
printf( "\n" );
#if UNSIGNED_INT
printf( "<A,B>;=<%u,%u>;\nmax=%u\n", _A, _B, uis() );
#else
printf( "<A,B>;=<%d,%d>;\nmax=%d\n", _A, _B, is() );
#endif
return 0;
} |
|