机器人 C语言

2025-05-16 00:41:08
推荐回答(1个)
回答(1):

这样写吧,清楚一点。
我觉得我这样定义的话会让程序清楚很多。
typedef struct
{
int x;
int y;
} pos_stru;

void main(void)
{
int cmd;
int face[4]={0,1,2,3}; //x+,y+,x-,y- 定义行进方向
int face_start=face[0]; //初始方向
pos_stru start={0,0}; //开始位置

while(scanf("%d",&cmd)!=NULL)
{
if(cmd==0)
break;

if(cmd<-2) //错误处理
{
printf("Invide input.");
}

switch(cmd) //先处理方向问题-1/-2
{
case -1: //左转
if(face_start<3)
face_start=face[face_start+1];
else
face_start=face[0];
break;
case -2: //右转
if(face_start>0)
face_start=face[face_start-1];
else
face_start=face[3];
break;
default:
break;
}

if(cmd>0) //不是方向的处理
switch(face_start)
{
case 0:
start.x+=cmd;
break;
case 1:
start.y+=cmd;
break;
case 2:
start.x-=cmd;
break;
case 3:
start.y-=cmd;
break;
default:
break;
}
//printf("tmp out:x=%d,y=%d\n",start.x,start.y);
}

printf("result:x=%d,y=%d\n",start.x,start.y);
}

out put:
-1
2
-2
1
0
result:x=1,y=2
Press any key to continue

问题补充:
没给定义应该是都初始化为0了吧~
答:不对。随机的这也是我们要求C语言必须初值的原因。下面是试验

void main(void)
{
int a;
int b=0;
printf("a=%d,b=%d\n",a,b);
}

output:
a=-858993460,b=0
Press any key to continue