题解 | 坐标移动
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29?tpId=37&tags=&title=&difficulty=0&judgeStatus=0&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37
#include <stdio.h> #include <stdlib.h> #include <string.h> int x = 0,y = 0;//设置坐标x,y的全局变量 int judge_legal(char *s,int n){//判断指令是否合法 if(n < 2 || n > 3){//先判断长度 return 0; } switch (s[0]) {//判断第一位是否为合法字母 case 'A':case 'D':case 'W':case 'S':break; default: return 0; } if(n == 3){//长度为3判断后两位是否是数字 if(s[1] - '0' < 0 || s[1] - '9' > 0 ||s[2] - '0' < 0 || s[2] - '9' > 0 ){ return 0; } } if(n == 2){//长度为2判断剩余一位是否是数字 if(s[1] - '0' < 0 || s[1] - '9' > 0 ){ return 0; } } return 1; } void coordinate(char *s){//计算坐标 char num[5]; int i; int a = 0; if(judge_legal(s, strlen(s)) != 0){//只对合法字符串操作 for(i = 1;i < strlen(s);i++){ num[i - 1] = s[i];//把数字部分取出 } num[i - 1] = '\0';//加上字符串结束标志 for(i = 0;i < strlen(num);i++){ a = a * 10 + (num[i] - '0');//把数组中的数字部分由字符变为数字 } switch (s[0]) {//根据移动方向计算坐标 case 'A':x -= a;break; case 'D':x += a;break; case 'W':y += a;break; case 'S':y -= a;break; } } } void cut_str(char * s,char *ch){ //使用strtok函数分割字符串,拿到指令 int len = 0; int i; char *token = NULL; token = strtok(s,ch);//strtok函数初次调用。功能是将ch中的字符作为分隔符,分割字符串 //分隔符会变为'\0',成功分割会返回子串的指针 while(token != NULL){ coordinate(token); token = strtok(NULL, ch); //strtok函数再次调用,第一个参数变为NULL } } int main() { char s[11000]; fgets(s,sizeof(s),stdin); cut_str(s, ";"); printf("%d,%d",x,y); return 0; }
C语言编程练习 文章被收录于专栏
菜鸟使用C语言的方法完成华为od练习题的过程