编程之美_1.2中国象棋将帅问题

解法一:

#include <stdio.h>
#define HALF_BITS_LENGTH 4//记忆存储单元的一半,此处为4bit
#define FULLMASK 255//表示二进制的11111111
#define LMASK (FULLMASK<<HALF_BITS_LENGTH)//表示11110000
#define RMASK (FULLMASK>>HALF_BITS_LENGTH)//表示00001111
#define RSET(b,n) (b=(LMASK&b)|n)//将b的右边设置为n
#define LSET(b,n) (b=((RMASK&b)|(n<<HALF_BITS_LENGTH)))//将b的左边设置为n
#define RGET(b) (RMASK&b)//得到b的右边的值
#define LGET(b) ((LMASK&b)>>HALF_BITS_LENGTH)//得到b的左边的值
#define GRIDW 3//移动范围的行宽度
int main()
{
	unsigned char b;
	for (LSET(b, 1); LGET(b) <= GRIDW*GRIDW; LSET(b, LGET(b) + 1))
	{
		for (RSET(b, 1); RGET(b) <= GRIDW*GRIDW; RSET(b, RGET(b) + 1))
		{
			if (LGET(b) % GRIDW != RGET(b) % GRIDW)
				printf("A=%d,B=%d\n", LGET(b), RGET(b));
		}
	}
	system("pause");
	return 0;
}

解法二:

#include <stdio.h>

int main()
{
	unsigned char i = 81;
	while (i--)
	{
		if (i / 9 % 3 == i % 9 % 3)//i/9表示外循环,i%9表示内循环
			continue;
		printf("A=%d,B=%d\n", i / 9 + 1, i % 9 + 1);
	}
	system("pause");
	return 0;
}

解法三:

#include <stdio.h>

int main()
{
	struct
	{
		unsigned char a : 4;
		unsigned char b : 4;
	}i;
	for (i.a = 1; i.a <= 9; i.a++)
	{
		for (i.b = 1; i.b <= 9; i.b++)
		{
			if (i.a % 3 != i.b % 3)
				printf("A=%d,B=%d\n", i.a, i.b);
		}
	}
	system("pause");
	return 0;
}

    原文作者:田爽Poison
    原文地址: https://blog.csdn.net/u012552052/article/details/42932083
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞