[编程之美]中国象棋将帅问题

熟悉位操作符和位的存储方法

View Code
 1 #include <stdio.h>
2
3 #define LMASK (255 << 4)
4 #define RMASK (255 >> 4)
5 #define LGET(d) ((d&LMASK) >> 4)
6 #define RGET(d) (d&RMASK)
7 #define LSET(d,n) (d=((d&RMASK) | (n << 4)))
8 #define RSET(d,n) (d=((d&LMASK) | n))
9
10 int main()
11 {
12 unsigned char b=0;
13 for(LSET(b,1);LGET(b)<=9;LSET(b,(LGET(b)+1)))
14 for(RSET(b,1);RGET(b)<=9;RSET(b,(RGET(b)+1)))
15 if(LGET(b)%3!=RGET(b)%3)
16 printf("A=%d,B=%d\n",LGET(b),RGET(b));
17 return 0;
18 }

 

还有一种更为简单明了的方法

View Code
 1 struct 
2 {
3 unsigned char a:4;
4 unsigned char b:4;
5 }chess;
6
7 int main()
8 {
9 for(chess.a=1;chess.a<=9;++chess.a)
10 for(chess.b=1;chess.b<=9;++chess.b)
11 if(chess.a%3!=chess.b%3)
12 printf("A=%d,B=%d\n",chess.a,chess.b);
13 return 0;
14 }

 

你可能感兴趣的:(编程之美)