后面两种写法很巧妙。一种利用位域,一种利用取余。
这里如果不用unsigned char来做位域的话,大小就为4. unsigned char才符合题目要求。
1 void chess1() { 2 struct { 3 unsigned char a:4; 4 unsigned char b:4; 5 } i; 6 cout << "sizeof(i): " << sizeof(i) << endl; 7 for (i.a = 1; i.a <= 9; i.a++) { 8 for (i.b = 1; i.b <= 9; i.b++) { 9 if (i.a % 3 == i.b % 3) continue; 10 cout << (int)i.a << " " << (int)i.b << endl; 11 } 12 } 13 } 14 15 void chess2() { 16 for (char n = 80; n >= 0; --n) { 17 if (n / 9 % 3 == n % 9 % 3) continue; 18 cout << n / 9 + 1 << " " << n % 9 + 1 << endl; 19 } 20 }