题目:
Description
机器人站在笛卡尔坐标系的原点,面向y轴正方向,给定若干指令,求机器人最终位置。
Input
多组测试数据,每组数据第一行为m,表示有m个操作,0 < m < 100。
接下来m行,每行一个指令。
指令格式:
“TURN”:右转90度。
“GO” NUM:直走NUM的距离。
Output
每组数据对应一行输出机器人最终所在的坐标,空格隔开,保留3位小数。
数据保证最终结果可以用double精确表示。
Sample Input
3 TURN GO 1 TURN
Sample Output
1.000 0.000
代码:
#include<iostream>
#include<string>//substr()
#include<cstdlib>//atof
#include<iomanip>//fixed
using namespace std;
string str;
int direction;//0表示y正,1 x正,2 y负,3 x负
void position(double &, double &, string);//void position(double , double);
int main()
{
int n;
while (cin >> n)
{
//double x = 0; double y = 0;//double x, y = 0;
//int n; cin >> n;
direction = 0;
double x = 0; double y = 0;
cin.ignore(0x7fffffff, '\n');
for (int i = 0; i < n; i++)
{
getline(cin, str);
//cout << str[i];
position(x, y, str);
}
cout << fixed << setprecision(3) << x << " " << y << endl;
}
return 0;
}
void position(double &x, double &y, string s)
{
if (s == "TURN")
{
direction = (direction + 1) % 4; //(direction + 1) / 4;
return;
}
if (s.substr(0, 2) == "GO")
{
if (direction == 0) y = y + atof(s.substr(3).c_str());
else if (direction == 1) x = x + atof(s.substr(3).c_str());
else if (direction == 2) y = y - atof(s.substr(3).c_str());
else x = x - atof(s.substr(3).c_str());
}
}