题目:开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。
思路:先检查当前组数据是否合法,再将其移动值(字符串)转化成数值,再判断并计算。
心得体会:一定要注意细节,特别是判断语句,
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 10000
void move(char,int);
int result[2] = {0};
int main()
{
char str[MAX] = {0},tmp[3];
int i,j,len,step;
step = 0;
while(fgets(str,MAX,stdin))
{
len = strlen(str);
str[len--] = '\0';
for(i = 0;i < len;)
{
memset(tmp,0,3);
if(i == 0)
{
j = i;
i =1;
}
else
{
while(str[i++] != ';');
j = i ;
}
if((str[j] == 'A'
|| str[j] == 'D'
|| str[j] == 'W'
|| str[j] == 'S'))
if((str[j+1] >= '0' && str[j+1] <= '9'))
if((str[j+2] >= '0' && str[j+2] <= '9'))
{
if(str[j+3] == ';')
{
tmp[0] = str[j+1];
tmp[1] = str[j+2];
}
else
continue;
}
else if(str[j+2] == ';')
{
tmp[0] = str[j+1];
}
else
continue;
else
continue;
else
continue;
step = atoi(tmp);
move(str[j],step);
}
printf("%d,%d\n",result[0],result[1]);
memset(result,0,sizeof(result));
//result[0] = 0;
//result[1] = 0;
}
return 0;
}
void move(char dir,int step)
{
switch(dir)
{
case 'A':
result[0] -= step;
break;
case 'D':
result[0] += step;
break;
case 'W':
result[1] += step;
break;
case 'S':
result[1] -= step;
break;
default:
break;
}
}