题解 | #坐标移动#

坐标移动

https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

思路:
        依序读取输入的数据,跳过所有分号。读取第一个字母(移动方向)之后,连续读取一个数字和符号,通过判断数字是否是两位数以内,以及该符号是否是分号,来保证移动幅度的数据是有效的。
随后通过检验移动方向是否为WSAD之一来判断是否为有效方向。


#include <stdio.h>
#include <string.h>

typedef struct {
    int x;
    int y;
}Coordinate;

int main(){
    
    char dirct;                  //临时存储方向
    int move = 0;                //临时存储幅度
    Coordinate point = {0,0};    //坐标初始化
    
    while( (dirct = getchar()) != '\n' ){
        //跳过所有分号 
        if(dirct == ';')
            continue;
        //判断坐标幅度是否合法,保证全数字且两位数以内
        char flag = 0;
        scanf("%d%c", &move, &flag);
        if(flag != ';' || move<-99 || move>99 ) continue;
        //判断坐标方向是否合法 
        if( strchr("WSAD", dirct) != NULL){
            switch(dirct){
                case 'A': point.x -= move; break;    //左移
                case 'D': point.x += move; break;    //右移
                case 'W': point.y += move; break;    //上移
                case 'S': point.y -= move; break;    //下移
                default : break;
            }
        }
    }
    
    printf("%d,%d\n", point.x, point.y);
    
    return 0;
}


全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务