问题
A,B二子被限制在己方3 X 3的格子里运动,A,B分别可以横向或纵向移动,但不能沿对角线移动且A,B不能处于同一纵向直线上。请写出一个程序,输出A、B所有的合法位置,要求在代码中只能使用一个字节存储变量。
image.png
不考虑题目只能使用一个字节存储的限制
#include<stdio.h>
int main(void)
{
int i,j;
for (i = 1; i <= 9; i++)
for(j = 1; j <= 9; j++)
{
if((i % 3 == 0) && (j % 3 != 0))
printf("A = %d, B = %d\n",i,j);
else if ((i % 3 == 1)&&(j % 3 != 1))
printf("A = %d, B = %d\n",i,j);
else if ((i % 3 == 2) && (j %3 != 2))
printf("A = %d, B = %d\n",i,j);
}
return 0;
}
这种方法最为笨拙,效率也不会高
缩短一些
使用字节类型变量
int main(void)
{
BYTE i = 81;
while(i--)
{
if (i / 9 % 3 == i %9 %3)
continue;
printf("A = %d, B = %d\n",i / 9 + 1, i % 9 + 1);
}
return 0;
}
最高效方法
#include<stdio.h>
struct {
unsigned char a:4;
unsigned char b:4;
} item;
int main(void)
{
for (item.a = 1; item.a <=9; item.a++)
for (item.b = 1; item.b <= 9; item.b++)
if(item.a % 3 != item .b % 3)
printf("A = %d, B = %d\n",item.a,item.b);
return 0;
}