C言語 坐標挪動詳解及實例代碼。本站提示廣大學習愛好者:(C言語 坐標挪動詳解及實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是C言語 坐標挪動詳解及實例代碼正文
標題描繪
開發一個坐標計算工具, A表示向左挪動,D表示向右挪動,W表示向上挪動,S表示向下挪動。從(0,0)點開端挪動,從輸出字符串外面讀取一些坐標,並將最終輸出後果輸入到輸入文件外面。
輸出:
合法坐標為A(或許D或許W或許S) + 數字(兩位以內)
坐標之間以;分隔。
合法坐標點需求停止丟棄。如AA10; A1A; $%$; YAD; 等。
上面是一個復雜的例子 如:
A10;S20;W10;D30;X;A1A;B10A11;;A10;
處置進程:
終點(0,0) + A10 = (-10,0) + S20 = (-10,-20) + W10 = (-10,-10) + D30 = (20,-10) + x = 有效 + A1A = 有效 + B10A11 = 有效 + 一個空 不影響 + A10 = (10,-10)
後果 (10, -10)
輸出描繪:
一行字符串
輸入描繪:
最終坐標,以,分隔
輸出例子:
A10;S20;W10;D30;X;A1A;B10A11;;A10;
輸入例子:
10,-10
Code:
#include<iostream>
#include<string>
using namespace std;
bool isValid(string s, char &key, int &step){
if (s.size()<2 || s.size()>3)return false;
if (s[0] != 'A' && s[0] != 'D' && s[0] != 'W' && s[0] != 'S')
return false;
key = s[0];
if (s.size() == 2 && s[1] >= '0' && s[1] <= '9'){
step = s[1] - '0';
return true;
}
if (s.size() == 3 && s[1] >= '0' && s[1] <= '9' && s[2] >= '0' && s[2] <= '9'){
step = (s[1] - '0') * 10 + (s[2] - '0');
return true;
}
return false;
}
void caculator(string s, int &x, int &y, char key, int step){
switch (key){
case 'A':
x -= step;
break;
case 'D':
x += step;
break;
case 'W':
y += step;
break;
case 'S':
y -= step;
break;
}
return;
}
int main(){
string str;
while (cin >> str){
int x = 0;
int y = 0;
int i = 0;
while (i<str.size()){
string temp;
char key;
int step;
while (str[i] != ';'){
temp.push_back(str[i]);
i++;
}
if (isValid(temp, key, step))
caculator(temp, x, y, key, step);
i++;
}
cout << x << ',' << y<<endl; //must add endl(wtf...,waste time)
}
return 0;
}
感激閱讀,希望能協助到大家,謝謝大家對本站的支持!